File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# Bit Shifting Question

Tom Purl
Ranch Hand

Joined: May 24, 2002
Posts: 104
I came across the following exercise in a book and am pretty confused by it:

The answer ends up being -1. If I understand bit shifting correctly, doesn't the following equation:

..equate to:
-1 / (2^31)
...which would be closer to zero?
Thanks in advance for any help!

Tom Purl<br />SCJP 1.4
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
The bit representation of -1 is
11111111 11111111 11111111 11111111
>> is the signed right shift operator. That means that it shifts the bits to the right (the number of times according to the second operand) and preserves the sign of the integer during each shift.
So, -1 >> anything is -1. All of the bits are 1's and are moved to the right, the left most bit being replaced by a new 1 during each shift.
For a more thorough explanation of bit shifting, take a look at Cat and Mouse Games with Bits.
Good Luck.

I agree. Here's the link: http://aspose.com/file-tools

subject: Bit Shifting Question