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?
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 value0x1f
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With