Win a copy of Functional Reactive Programming this week in the Other Languages forum!

Odd Left Shift

Craig Oliver
Greenhorn
Posts: 21
Following gives a result of 10. I was expecting 0. I understand byte is converted to int before shift and int is 32 bit, but thought would have all 0 bits. Any advice appreciated. I realise (5<<1) also gives 10.
public class Q5
{
public static void main(String args[])
{
byte b = 5;
System.out.println(b<<33);
}
}

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24212
35
If you shift by more than 31 bits, the shift is taken modulo-32; shifting by 33 bits is equivalent to shifting by 1 bit. JLS section 15.19:
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 value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?