-1 left shift by 31

System.out.println((-1<<31)); 

Why does this give a result -2147483648

I know that -1 <31 will give 10000000000000000000000000000000, so it should give ans (int)Math.pow(2,31) equal to 2147483648

+7
java bit-manipulation
source share
3 answers

-1<<31 gives 10000000000000000000000000000000 , which is -2147483648 , not 2147483648 . Note that the left bit is a sign bit, so if it is 1, it is a negative number.

BTW, 1<<31 will also give you -2147483648 , since 2147483648 higher than Integer.MAX_VALUE . On the other hand, 1L<<31 will give you 2147483648 , as the result will be long .

+7
source share

I know that -1 <31 will give 100000000000000000, so it should give ans (int) Math.pow (2.31) value equal to 2147483648

That would be so if int was a two-component unsigned primitive; but int signed.

You are correct in the fact that in binary it really gives what you say; however, since this is a signed two-component primitive, the result will be x (0) * 2 ^ 0 + x (1) * 2 ^ 1 + ... + x (n-2) * 2 ^ (n-2) - x ( n-1) * 2 ^ (n-1) (minus, not plus), where x(y) is the value of the y-th bit, counting from 0.

Therefore, your result.

+4
source share

Currently, in most architectures, numbers are stored in 2 additions, see Wikipedia .

So your result is correct. The bit sign is set, and all remaining zeros (because the 2-complement) makes this the most negative number for this data type, see here .

2-Add-on Thinking

 -1 is represented by 1111 1111 1111 1111 1111 1111 1111 1111 

31 left shift gives

 1000 0000 0000 0000 0000 0000 0000 0000 which represents -2.147.483.648 
+3
source share

All Articles