在java中使用右移运算符时,我遇到了一个奇怪的情况.当我将16向右移位31时,它会导致0然而在尝试右移16乘32时它仍然是16.有人可以解释一下,因为我疯了.
public class RightShiftTest {
public static void main(String args[]) {
int b = 16;
System.out.println("Bit pattern for int " + b + " is " +Integer.toBinaryString(b));
// As expected it is 0
System.out.println("After right-shifting " + b + " for 31 times the value is " + (b>>31) + " and bit pattern is " +Integer.toBinaryString(b>>31));
// But why is it not 0 but 16
System.out.println("After right-shifting " + b + " for 32 times the value is " + (b>>32) + " and bit pattern is " +Integer.toBinaryString(b>>32));
}
}
Output:
Bit pattern for int 16 is 10000
After right-shifting 16 for 31 times the value is 0 and bit pattern is 0
After right-shifting 16 for 32 times the value is 16 and bit pattern is 10000
Run Code Online (Sandbox Code Playgroud)
Sot*_*lis 10
在Java语言规范状态
如果左手操作数的提升类型是
int,则只使用右手操作数的五个最低位作为移位距离.就好像右手操作数受到&带有掩码值0x1f(0b11111)的按位逻辑AND运算符(第15.22.1节)的影响.因此,实际使用的移位距离始终在0到31的范围内,包括0和31.
值32表示为
100000
Run Code Online (Sandbox Code Playgroud)
最低的5位是00000这样0,移位0位.
| 归档时间: |
|
| 查看次数: |
581 次 |
| 最近记录: |