aspose file tools
The moose likes Beginning Java and the fly likes Bit Shifting Question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Bit Shifting Question" Watch "Bit Shifting Question" New topic
Author

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.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Bit Shifting Question
 
Similar Threads
Doubt in Shift operator
Right Shift Operator >>
short to bit ?
bit values of an integer
HexString