-
32768+1 = -32768 ???
I am just starting with C, and in most languages you get overflow or some error about integer overflow or something....
My question is, why does C go to -32768, and then counts up to 0, then to +32768 again, and it becomes a constant loop.
I thought it would have something to do with binary, and that:
11111
when added, if you only have x spots, it becomes
00000
I may be wrong, but any explanation is appreciated! :)
-
Test to add unsigned in front of the declaration of the integer, that will make the integer 0-based.
-
Code:
int i; - this means it interprets the most significant bit as +/-
unsigned int j; this means it does not interpret that bit as a sign
Hence you can reach a higher absolute value with j than with i;
-
Yes, I understand that unsigned can go up to 65xxx
but my question is, WHY does it go go 32767, 32768, -32768, -32767
thanks.
-
-
You've already answered it. The solution lies in the bits. It simply wraps around.
-
but if 11111 become 00000, why does it start again at -, and not at 0 ?
-
Because of the format used to represent negative numbers. It's called 1's complement.
11111111 is -1, not -32,some as one would think.
To get the negative of any number you invert every bit, then add 1.
00100011 (35) -> 11011100+1=11011101 (-35)
00000001 (1) -> 11111110+1=11111111 (-1)
00000000 (0) -> 11111111+1=00000000 (0)
Whenever the CPU needs a substraction, it converts the number to be substracted to negative and adds it:
5-1
00000101 - 00000001 = 00000101 + 11111111 = 00000100 (with the highest 1 being cut off) = 4
-
The highest positive number is 01111111 (127), the highest negative is 10000000 (-128). If you add 1 to 127 you get -128
-
-
The highest number for signed 16 bit integers is 32767 (2^15-1) instead of 32768. This is because of the existance of zero.
-32768 is still the lowest value.