Because the default 1 here is int 类型。而你的编译环境下,int` is 32-bit. Then the binary representation of this 1 is
0000 0000 0000 0000 0000 0000 0000 0000 0001
After shifting left by 32 bits
1000 0000 0000 0000 0000 0000 0000 0000 0000
Because it is of int type, it is signed. So the first bit is the sign bit, which is a negative number. Why is it the minimum value of int? Because it is expressed using complement code.
If you need to move out of the maximum value, use the following method
((unsigned int)-1) >> 1
Because the binary representation of -1 is 0xffffffff. If you convert it to an unsigned type and then shift it, there will be no impact of the sign bit.
For a 32-bit int, shifting 31 bits left will reach the highest bit For a signed number, the highest bit is the sign bit, 0 is positive and 1 is negative, so it becomes the minimum value. The specific reason can be Take a look at how int is stored
Because the default
1
here is int类型。而你的编译环境下,
int` is 32-bit.Then the binary representation of this
1
isAfter shifting left by 32 bits
Because it is of
int
type, it is signed. So the first bit is the sign bit, which is a negative number. Why is it the minimum value ofint
? Because it is expressed using complement code.If you need to move out of the maximum value, use the following method
Because the binary representation of
-1
is0xffffffff
. If you convert it to an unsigned type and then shift it, there will be no impact of the sign bit.The maximum int is 2 to the 31st power - 1, 1<<31 is out of range, and will be calculated backwards from the smallest negative number
For a 32-bit int, shifting 31 bits left will reach the highest bit
For a signed number, the highest bit is the sign bit, 0 is positive and 1 is negative, so it becomes the minimum value. The specific reason can be Take a look at how int is stored
(1 << 31) - 1 : The maximum value of signed int
(1 << 31) + 1 : The minimum value of signed int
((unsigned int)1<<32)-1: The maximum value of unsigned int
0: The minimum value of unsigned int
I tested it:
Compile:
gcc test.c -o test
,Run:
./test
Result:
Brother, remove the sign bit and shift it by 30 bits