5

Recently I was confused by this question. Maybe because I didn't read language specifications (it's my fault, I know).

C99 standard doesn't say which negative numbers representation should be used by compiler. I always thought that the only right way to store negative numbers is two's complement (in most cases).

So here's my question: do you know any present-day compiler that implements by default one's complement or sign-magnitude representation? Can we change default representation with some compiler flag?

What is the simplest way to determine which representation is used?

And what about C++ standard?

Community
  • 1
  • 1
klew
  • 14,837
  • 7
  • 47
  • 59
  • i guess you could determine which implementation is used by checking the binary of a signed value for its representation, similar to how endianness checks are done. this could probably be done in a #define and evaluated at compile time. – slipperyseal May 14 '15 at 04:49
  • i mean, if you haven't solved this problem in the last 6 years. :o – slipperyseal May 14 '15 at 04:51
  • [Is one's complement a real-world issue, or just a historical one?](https://stackoverflow.com/q/161797/995714) – phuclv May 29 '17 at 06:32
  • Possible duplicate of [Is one's complement a real-world issue, or just a historical one?](https://stackoverflow.com/questions/161797/is-ones-complement-a-real-world-issue-or-just-a-historical-one) – phuclv May 29 '17 at 06:34

3 Answers3

5

I think it's not so much a question of what representation the compiler uses, but rather what representation the underlying machine uses. The compiler would be very stupid to pick a representation not supported by the target machine, since that would introduce loads of overhead for no benefit.

Some checksum fields in the IP protocol suite use one's complement, so perhaps dedicated "network accelerator"-type CPU:s implement it.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

The UNISYS 2200 series which implements one's complement math, is still in use with some quite updated compiler. You can read more about it in the questions below

phuclv
  • 37,963
  • 15
  • 156
  • 475
1

While twos-complement representation is by far the most common, it is not the only one (see some). The C and C++ standardisation committees did not want to require non-twos-complement machines to emulate a non-native representation. Therefore neither C not C++ require a specific negative integer format.

This leads to the undefined behaviour of bitwise operations on signed types.

Richard
  • 106,783
  • 21
  • 203
  • 265
  • Yes, but it's not what I am asking about. Do you know any C compiler that by default would use non-two's complemet? – klew Apr 01 '09 at 10:56
  • Those for systems which use non-tows-complement... Which, apparently, includes some Unisys box which is still supported (this might be listed in the second link). – Richard Apr 01 '09 at 13:47