Shifted by negative number in java

老子叫甜甜 提交于 2019-11-29 11:23:14

From the JLS, section 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.

Now -63 & 0x1f == 1, So this is actually a shift by 1 to the right, hence the answer of 4.

s = s >>-63; is like s = s >> 1; (-63 % 32)

Take a look at the shift operator behavior at the JLS §15.19.

    int s=8;        
    Assert.assertEquals(s >>-63, s >>-63 % 32);
    Assert.assertEquals(s >>-63, s >>-31);
    Assert.assertEquals(s >>-31, s >>32 -31);
    Assert.assertEquals(s >>32 -31,s >>1); 
    Assert.assertEquals(s >>1,s /2); 
    Assert.assertEquals(s/2,4); 

The following 2 statements are producing one and the same result for integers if you want to replace negative shift:

r << -shift

and

r << ((32 - shift) % 32)

(32 is the size of integer in Java)

Shifting with -63 actually shifts with -63 & 0x1f == 1 for int or -63 & 0x3f == 1 for long, because in Java shifting left with >> uses sign-extension, and 1 will shift out any zero bits in the case of 8.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!