Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is (-1 >>> 32) = -1? [duplicate]

Possible Duplicate:
why is 1>>32 == 1?

-1 as an int converted to binary is represented by 32 1's. When I right-shift it 31 times, I get 1 (31 0's and one 1). But when I right-shift it 32 times, I get -1 again. Shouldn't it be equal to 0?

like image 839
user183037 Avatar asked Jan 27 '11 07:01

user183037


1 Answers

The Java specification explains the shift operators as follows:

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

The value of 32 & 0x1f is zero.

If the left operand is long, then you get an extra bit for the right operand, expanding the upper limit to 63 instead of 31.


In order to have any specific expected value from shifting -1 to the right, you need to specify the underlying binary representation of integers (e.g., two's complement) as well as the number of bits (e.g., 32). Each programming language can define those differently, but in the interest of keeping things simpler for the implementation, they'll usually specify that shifting by more than the number of available bits is not allowed. That's often because the underlying CPU hardware doesn't support it, either. After all, if you want to shift that many bits, the left operand no longer matters since the result will always be the same.

like image 82
Rob Kennedy Avatar answered Oct 23 '22 01:10

Rob Kennedy