posted 24 years ago
Anjo,
It seems that in this case, because the left-hand operand is int, only the first 5 bits (the least significant) of the right-hand operand are used. This ensures that the shifting will be in the range 0-31 (and effectivly strips off the high-order bit, making the right-hand operand 31, and not -1). So, you are effectively doing i >>= 31. Take a look at this (from the JDK documentation) ...
---
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.21.1) with the mask value 0x1f. The shift distance actually
used is therefore always in the range 0 to 31, inclusive.
If the promoted type of the left-hand operand is long, then only the six 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.21.1) with the mask value 0x3f. The shift distance
actually used is therefore always in the range 0 to 63, inclusive.
---
"Can u shift by negative numbers?" I don't know how to answer that ... yes, you seemingly can shift by negative numbers, because there will be no errors, but you're not really shifting in the opposite direction - the direction of the shift will remain the same.
Hope that helps!
Greg