I came across a weird looking situation while using right-shift operator in java. When I right-shift 16 by 31 it results in 0 however on trying to right-shifting 16 by 32 it remains 16 itself. Could someone please explain it as I am going crazy over it.
public class RightShiftTest {
public static void main(String args[]) {
int b = 16;
System.out.println("Bit pattern for int " + b + " is " +Integer.toBinaryString(b));
// As expected it is 0
System.out.println("After right-shifting " + b + " for 31 times the value is " + (b>>31) + " and bit pattern is " +Integer.toBinaryString(b>>31));
// But why is it not 0 but 16
System.out.println("After right-shifting " + b + " for 32 times the value is " + (b>>32) + " and bit pattern is " +Integer.toBinaryString(b>>32));
}
}
Output:
Bit pattern for int 16 is 10000
After right-shifting 16 for 31 times the value is 0 and bit pattern is 0
After right-shifting 16 for 32 times the value is 16 and bit pattern is 10000
The Java Language Specification states
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
(0b11111
). The shift distance actually used is therefore always in the range 0 to 31, inclusive.
The value 32 is represented as
100000
the lowest 5 bits are 00000
so 0
, shifted by 0 bits.
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