Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilers and negative numbers representations

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?

like image 215
klew Avatar asked Apr 01 '09 10:04

klew


People also ask

How are negative numbers represented?

Negative numbers are usually written with a minus sign in front. For example, −3 represents a negative quantity with a magnitude of three, and is pronounced "minus three" or "negative three".

How are negative numbers represented in computer memory?

Negative number are stored as signed number where last bit on left is sign bit, if it is 1 then its negative 0 mean positive, remaining bits are data bit which are compliment of the positive bit.

How does C++ represent negative numbers?

C++ supports integral values both "signed" (positive or negative) and "unsigned" (never negative). The only difference is the value represented by the highest bit. The highest bit is often called the "sign bit" because if it's 0, the number is positive, and if it's 1, the value is negative (for signed values).


3 Answers

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.

like image 149
unwind Avatar answered Sep 30 '22 08:09

unwind


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.

like image 33
Richard Avatar answered Sep 30 '22 07:09

Richard


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

  • Exotic architectures the standards committees care about
  • Are there any non-twos-complement implementations of C?
like image 30
phuclv Avatar answered Sep 30 '22 07:09

phuclv