• 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

Unsigned right shift

 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Everybody,
Can anybody explain the output of the following program for me?

The output is -1.
For unsigned right shift, since sign is not honoured, zeros are filled in the vacancies created in the MSB position for each shift to the right. If I am not wrong, since the bit size of int is 32, after 32 shifts, all the 32 bits would be replaced by zeros. The output should've been zero. I think that my understanding of this is wrong. Can anybody help me with some explanation?
Thanks.
Kezia.
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Kezia
Your understanding is right however, before it performs a shift the java performs a bitwise & on the right hand operand with a mask of 0x1F for ints and 0x3F for longs. For a positive number this is equivalent to doing a %32 or %64.
So, if you're right hand operand is 32, then 32%32 is 0 and no shift is performed.
If you want a detailed explaination check out the JLS section 15.19
for an easier to see example try to do a shift of 33 or 34 and you see that the shift is actually 1 or 2.
hope that helps

------------------
Dave
Sun Certified Programmer for the Java� 2 Platform
 
Kezia Matthews
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Thanks Dave for the quick reply.
Kezia.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic