programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Shift operators - question

ramki srini
Greenhorn
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
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
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.