Java奇异程序输出中的Shift运算符 [英] Shift operator in Java bizarre program output

查看:190
本文介绍了Java奇异程序输出中的Shift运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下程序,它表现得出乎意料。

I came across the following program and it behaving in unexpected manner.

public class ShiftProgram
{
      public static void main(String[] args)
      {
             int i = 0;
             while(-1 << i != 0)
                   i++;
             System.out.println(i);
      }
}

如果我们考虑这个程序输出,当它到达时32 while循环条件应该返回false并终止,它应该打印32。

If we think about this program output, when it reaches 32 while loop condition should return false and terminate and it should print 32.

如果你运行这个程序,它不打印任何东西,但会进入无限循环。有什么想法吗?先感谢您。

If you ran this program, it does not print anything but goes into an infinite loop. Any idea whats going on? Thank you in advance.

推荐答案

您是否尝试过打印( - 1<<< i)在循环中看看出了什么问题?如果你这样做,你会看到它:

Have you tried printing out (-1 << i) in the loop to see what's going wrong? If you do, you'll see that it goes:

-1 << 0 = -1
-1 << 1 = -2
-1 << 2 = -4
-1 << 3 = -8
-1 << 4 = -16
-1 << 5 = -32
-1 << 6 = -64
-1 << 7 = -128
-1 << 8 = -256
-1 << 9 = -512
-1 << 10 = -1024
-1 << 11 = -2048
-1 << 12 = -4096
-1 << 13 = -8192
-1 << 14 = -16384
-1 << 15 = -32768
-1 << 16 = -65536
-1 << 17 = -131072
-1 << 18 = -262144
-1 << 19 = -524288
-1 << 20 = -1048576
-1 << 21 = -2097152
-1 << 22 = -4194304
-1 << 23 = -8388608
-1 << 24 = -16777216
-1 << 25 = -33554432
-1 << 26 = -67108864
-1 << 27 = -134217728
-1 << 28 = -268435456
-1 << 29 = -536870912
-1 << 30 = -1073741824
-1 << 31 = -2147483648
-1 << 32 = -1
-1 << 33 = -2
-1 << 34 = -4
-1 << 35 = -8
-1 << 36 = -16
[.. etc ..]

根据语言规范


n<< s的值是n个左移位s位;这相当于(即使发生溢出)乘以2乘以幂。

The value of n<<s is n left-shifted s bit positions; this is equivalent (even if overflow occurs) to multiplication by two to the power s.

...所以结果将始终保持不变否定。

... so the result will always remain negative.

该文件还告诉您:


如果是提升类型左侧操作数的值是int,只有右侧操作数的五个最低位用作移位距离。就好像右手操作数受到按位逻辑AND运算符& (§15.22.1),掩码值为0x1f。因此,实际使用的移动距离始终在0到31的范围内。

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

因此,如果您使用<$ c的班次$ c> 32 ,这被解释为 32& 0x1f ,即 0 -1 移动 0 仍然只是 -1 ,不是 0

So if you use a shift of 32, that's interpreted as a shift of 32 & 0x1f, which is 0. -1 shifted by 0 is still just -1, not 0.

这篇关于Java奇异程序输出中的Shift运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆