File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Odd Left Shift

 
Craig Oliver
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24204
34
Chrome Eclipse IDE Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic