• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Bit Shifting Question

 
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
reply
    Bookmark Topic Watch Topic
  • New Topic