Granny's Programming Pearls "inside of every large program is a small program struggling to get out" JavaRanch.com/granny.jsp
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login

# Shift operators - question

ramki srini
Greenhorn

Joined: Aug 27, 2002
Posts: 26
I tried this following code
class Q2{
public static void main(String args[])
{
int a = 5;
int b = -2;
int c=a>>b;
int d=a<<b;
int e=a>>>b;
System.out.println(+c);
System.out.println(+d);
System.out.println(+e);
}
}
After compilation and running I am getting the output as,
0
1073741824
0
Vin Kris
Ranch Hand

Joined: Jun 17, 2002
Posts: 154
Try this:- System.out.println( (5 >> -2) == (5 >> 30) );
JLS 15.19 Shift Operators
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.
Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
Hi Ramki:
Try these simple rules that cover most of the sitution. Please let me know if find they do not work in any situation:
Shift Operators
A op B
Assuming A is any integral value except long. For long A, replace 32 with 64:
1. B = B%32
2. If B is negative and not –32 : B=B+32
3. For signed right shift operator (>> , divide A successively by 2, B number of times. Round down the final result if A is positive. Round up the final result if A is negative.
4. For signed left shift operator (<< ; multiply A succesively by 2, B number of times. If (32-B)th bit of original A value is 1, make the result –ve if it is not already negative. If the final result is more than Integer.MAX_VALUE, make final result 0.
5. For unsigned right shift operator (>>> with postive A, same rules as number 3 above.
6. For unsigned right shift operator (>>> with negative A, do it conventional way:
a. find the 2’s compliment of negative A
b. right shift by B bits, inserting 0 on the left
c. find the decimal of above.

I agree. Here's the link: http://aspose.com/file-tools

subject: Shift operators - question