File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Odd Left Shift" Watch "Odd Left Shift" New topic
Author

Odd Left Shift

Craig Oliver
Greenhorn

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;
System.out.println(b<<33);
}
}
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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]
 
 
subject: Odd Left Shift
 
Similar Threads
Conversion Long to byte[]
image is not beeing drawn
for loop and byte to int coversion.
about >>> question
diff between += and =+ different output