Why in Java right shifting 16 by 32 results in 16 and not 0? 16 >> 32 = 16 Why?
I ran into a weird looking situation using the shift operator in java. When I shift from the right side by 16 by 31 it results in 0, but when I try to shift to the right 16 by 32 it remains 16. Can someone explain this because I am going crazy about this.
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
source to share
The Java Language Specification contains
If the promoted type is the left operand
int
, only the least significant five bits of the right operand are used as the offset distance. ... It is as if the right-hand operand was subjected to a bitwise logical AND operator&
(§15.22.1) with a mask value0x1f
(0b11111
). Thus, the actually used offset distance is always between 0 and 31, inclusive.
The value 32 is represented as
100000
lower 5 bits 00000
, therefore 0
, shifted by 0 bits.
source to share