Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question about ">>"

 
jeff yashero
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I wrote some codes like bellow...
//A program about shift">>"
public class Test1{
public static void main(String[] args){
int num=100;
num=num>>-2;
System.out.println("The result is:"+num);
}
}

Why the result equal to zero??
However I try this : " num=num>>(-2) " ,and I got the same answer...
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jeff,
Welcome to JavaRanch!
Please have a look at our naming policy -- I think "Jeff Jeff" falls under "obviously fictitious." Thanks. We try to keep things respectable 'round these parts.
Anyway, as to your question: from the Java Language Specification:

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (�15.22.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

So, since -2 & 0x1f is 0x1e, or 30, >> -2 is equal to right-shifting by 30 bits; enough to annihilate all the nonzero bits of decimal 100!
 
jeff yashero
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest ^^
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic