It's not a secret anymore!
The moose likes Beginning Java and the fly likes Odd Left Shift Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Odd Left Shift" Watch "Odd Left Shift" New topic

Odd Left Shift

Craig Oliver

Joined: Aug 25, 2003
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;
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Odd Left Shift
It's not a secret anymore!