Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java bitwise operator << [duplicate]

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
like image 549
nenito Avatar asked Mar 30 '16 09:03

nenito


2 Answers

-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.

like image 91
assylias Avatar answered Oct 24 '22 12:10

assylias


The shift count value is used modulo 32. So the second example is actually the same as shifting by 0.

like image 26
Henry Avatar answered Oct 24 '22 11:10

Henry