Question

I am just stuck with this small logic that i am not getting it right

int is 32 bits so suppose taking 20 in binary would be like

// 00000000000000000000000000010100    

.. now if I perform rightshift operation say 4

int a = 20>>4;   
// 00000000000000000000000000000001    

..so result is 1

Now say I again take 20 and do 5 right shift operation

int b = 20>>5;  //00000000000000000000000000000000    

..so result is 0

Now if I do 32 right shift ... why I am getting the same number as I assigned.??

int c = 20>>32; //how does this prints 20 again??

System.out.println("right shift 4= "+a+"\n right shift 5= "+b+"right shift 32 = "+c);

So what I was expecting is after 5 shifts ..any number of shifts should have resulted in the result 0.. but on 32 shifts why I am getting back the assigned value?

Was it helpful?

Solution 2

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 (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

If the promoted type of the left-hand operand is long, then only the six 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 0x3f (0b111111). The shift distance actually used is therefore always in the range 0 to 63, inclusive

OTHER TIPS

When you shift an int only the lower 5 bits of the shift are used. When you shift a long only the lowest 6 bits are used.

From the Java Language Specification section 15.19:

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 (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

If the promoted type of the left-hand operand is long, then only the six 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 0x3f (0b111111). The shift distance actually used is therefore always in the range 0 to 63, inclusive.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top