aspose file tools*
The moose likes Beginning Java and the fly likes A question about >"" title="World Series of Baseball" /> Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "A question about ">>"" Watch "A question about ">>"" New topic
Author

A question about ">>"

jeff yashero
Greenhorn

Joined: Sep 24, 2003
Posts: 5
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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!


[Jess in Action][AskingGoodQuestions]
jeff yashero
Greenhorn

Joined: Sep 24, 2003
Posts: 5
Thanks Ernest ^^
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: A question about ">>"