• Post Reply Bookmark Topic Watch Topic
  • New Topic

left shift and right shift  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,
i'm pretty new to java
i was goin through K&B and trying to solve an exercise and i had a question..

The question is

why does


int l = 1;
System.out.println(l<<31); // gives -2147483648
System.out.println(l>>31); // give 0 (i was expecting -1 )


and


int s = 1;
s <<= 31;
s >>= 31;
System.out.println(s);//gives -1


give different answers..?
I was expecting the same answer for both the snippets

[ August 01, 2008: Message edited by: Pranav Mantini ]
[ August 01, 2008: Message edited by: Bear Bibeault ]
 
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first example doesn't change the value of the int,the second example does.
For the first int the >> shift of 1 is 0.
For the second int, once the sign bit is set, >> shifting propagates it.
 
Pranav Mantini
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh i get it............!
thanks a lot for the help..............
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!