Why does an int up-shift bit result in a negative number?

I am new to bit manipulation tricks, and I wrote simple code to see the result of doing single bits of shifts by one number, namely. 2

 #include <iostream> int main(int argc, char *argv[]) { int num=2; do { std::cout<<num<<std::endl; num=num<<1;//Left shift by 1 bit. } while (num!=0); return 0; } 

The result of this is as follows.

 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 -2147483648 

Obviously, a continuous shift of bits to the left by 1 bit will lead to zero, as was done above, but why does the computer print a negative number at the very end before the end of the cycle (since num is reset)?

However, when I replace int num=2 with unsigned int num=2 , then I get the same result, except that the last number this time displays as positive, i.e. 2147483648 instead of -2147483648

I am using gcc compiler on Ubuntu Linux

+7
source share
3 answers

This is because int is a signed integer. In the two -s-complement view, the sign of the integer is determined by the topmost bit.

As soon as you move 1 to the most significant (sign) bit, it flips negatively.

When you use unsigned , there is no sign bit.

 0x80000000 = -2147483648 for a signed 32-bit integer. 0x80000000 = 2147483648 for an unsigned 32-bit integer. 

EDIT:

Note that strictly speaking, integer chain overflows are undefined behavior in C / C ++. The behavior of the GCC in this aspect is not entirely consistent:

+16
source

Good question! The answer is pretty simple.

The maximum integer value is 2^31-1 . 31 (not 32) exists for some reason - the last bit for an integer is used to determine if it is a positive or negative number.

If you continue to shift the bit to the left, you will eventually hit that bit and it will become negative.

Additional information: http://en.wikipedia.org/wiki/Signed_number_representations

+2
source

As soon as the bit reaches the signed bit of the signed one (the most significant bit), it becomes negative.

0
source

All Articles