Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Right Shift Operator Evaluation

 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What would be the answer to this and how is it getting evaluated>

 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To find out what the output of this is, you can ofcourse simply try it out.

A byte is an 8-bit signed integer. In the first line, you're setting the bits to 0xf1 (or 1111 0001 in binary).

In line 2 you're first shifting this to the right by 4 bits. When you shift a byte to the right, all the bits go right one place, the left rightmost bit will be discarded and the right leftmost bit will be copied from what was previously the right leftmost bit. So:

[1] 1111 0001 >> 1 = 1111 1000
[2] 1111 1000 >> 1 = 1111 1100
[3] 1111 1100 >> 1 = 1111 1110
[4] 1111 1110 >> 1 = 1111 1111

The result after >> 4 is: 1111 1111

Then you do a bitwise AND with 0x0f (or 0000 1111 in binary).

1111 1111 & 0000 1111 = 0000 1111

So the result is 0000 1111, which is 0x0f in hexadecimal or 15 in decimal.
 
Mohnish Khiani
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank You Sir..thanks a lot for your answer
 
Marshal
Posts: 79635
380
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Are you sure you had leftmost and rightmost the right way round, Jesper?
 
Jesper de Jong
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Fixed. At least I was consistently writing it wrong...
reply
    Bookmark Topic Watch Topic
  • New Topic