Can someone explain why the following bitwise expressions return different results:
System.out.println((-1<<31)<<1); // it prints 0
System.out.println(-1<<32); // it prints -1
Can someone explain why the following bitwise expressions return different results:
System.out.println((-1<<31)<<1); // it prints 0
System.out.println(-1<<32); // it prints -1
-1<<32
is equivalent to -1<<0
, i.e. a no-op. The reason is that the shift distance (32)
is AND-ed with 0x1f
and 32 & 0x1f
is 0.
This is defined in the JLS #15.19 (emphasis mine):
If the promoted type of the left-hand operand is int, then 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 (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.
The shift count value is used modulo 32. So the second example is actually the same as shifting by 0.