Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Shift Operators

 
Arsho, Ayan
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<code>
Hello All :
Why does this piece of code output '-1' ?
int i = 1;
i <<= 31;<br /> i >>= 31;
i >>= 1;
S.O.P (i) is -1
Is it because when the shift occurs first time '<<=' the MSB remains 1???
</code>
[This message has been edited by Arsho, Ayan (edited December 07, 2001).]
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int i=1; // i = 00000000 00000000 00000000 00000001
i <<= 31; // i = 10000000 00000000 00000000 00000000<br /> i >>= 31; // i = 11111111 11111111 11111111 11111111 because this is a signed right-shift
i >>= 1; // i = 11111111 11111111 11111111 11111111
And now i is 0xFFFFFFFF which is -1.
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic