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
  • 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: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class shifting{
public static void main (String args[])
{
byte b = -13; //11110011
b >>>= 1; //01111001
System.out.println(b);
}
}
I get the answer as 121
But the correct answer is b= -7
Can anyone explain this please.

Thanks,
vijaya
[ June 22, 2004: Message edited by: vijaya dev ]
 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
byte b = -13; //11110011
b >>>= 1;

when you perform a shift operation the value
is promoted to at least an int so you get
11111111 11111111 11111111 11110011
after the shift you have:
01111111 11111111 11111111 11111001
if you chop off the higer 24 bits
you remain with 11111001
which is -7!

(use two's complement to get the value in base 10:
11111001
1 - flip bits -->00000110
2 - add one -->00000111, which is 7
but you have to add the minus since it's negative)

[ June 22, 2004: Message edited by: Lukas Alamar ]
[ June 22, 2004: Message edited by: Lukas Alamar ]
 
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Link
 
vijaya dev
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your reply. Now I can understand more clearly.
 
Beauty is in the eye of the tiny ad.
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic