File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Elasticsearch in Action this week in the Big Data forum!
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: 24189

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