加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java奇异程序输出中的Shift运算符

发布时间:2020-12-15 04:54:20 所属栏目:Java 来源:网络整理
导读:我遇到了以下程序,它表现得出乎意料. public class ShiftProgram{ public static void main(String[] args) { int i = 0; while(-1 i != 0) i++; System.out.println(i); }} 如果我们考虑这个程序输出,当它达到32时,循环条件应该返回false并终止,它应该打印3
我遇到了以下程序,它表现得出乎意料.

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

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

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

解决方法

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

-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 ..]

根据language specification:

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.

……所以结果总是保持负面.

那份文件还告诉你:

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.

因此,如果您使用32的移位,则将其解释为32和32的移位. 0x1f,即0.1移位0仍然只是-1,而不是0.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读