GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Shift operators - question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Shift operators - question" Watch "Shift operators - question" New topic

Shift operators - question

ramki srini

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;
After compilation and running I am getting the output as,
Pls explain me the answer.
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.
GeeCON Prague 2014
subject: Shift operators - question