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 shifting bits of -1 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "shifting bits of -1" Watch "shifting bits of -1" New topic
Author

shifting bits of -1

Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
I have been experimenting with shifting bits around. For example, if I do

-1 << 24

I get a number, when written out in bits is

11111111000000000000000000000000

However, I did this

-1 << 32

and expected

00000000000000000000000000000000

However, I got this:

11111111111111111111111111111111

Why?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14111
    
  16

That's because when you shift an int 32 times, it will really be shifted 0 times instead of 32 times.

Section 15.19 of the Java Language Specification explains this:

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.

If the promoted type of the left-hand operand is long, then only the six 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 0x3f. The shift distance actually used is therefore always in the range 0 to 63, inclusive.


So, in the case of an int, only the lowest five bits of the shift distance are used. The lowest five bits of the number 32 are all 0, so the real shift distance is 0 (32 & 0x1f = 0).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: shifting bits of -1