Shift right in Java

I just stick to this little logic. I didn't do it right

Int is 32 bits, so assume that binary 20 is like

// 00000000000000000000000000010100

.. Now, if I perform a shift right operation, say 4

int a = 20>>4;   
// 00000000000000000000000000000001

.. The result is 1

Now let me take 20 again and do 5 right shifts

int b = 20>>5;  //00000000000000000000000000000000

.. The result is 0

Now, if I do 32 right shifts... Why do I get the same number as I specified

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 expect is after class 5 Any shift should result in a result of 0 But why should I return to the specified value on shift 32?

Solution

JLS 15.19. Shift Operators

If the promotion type of the left operand is int, only the five lowest bits of the right operand are used as the shift distance It is as if the right-hand operand is subjected to a bitwise logical and operator & (§ 15.22.1) with a mask value of 0x1f (0b11111) Therefore, the shift distance actually used is always in the range of 0 to 31, including 0 and 31

If the lift type of the left operand is very long, only the six lowest bits of the right operand are used as the shift distance It is as if the right-hand operand is subjected to the bitwise logical and operator & (§ 15.22.1), and the mask value is 0x3f (0b111111) Therefore, the shift distance actually used is always in the range of 0 to 63, including 0 and 63

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>