按位运算和溢出

huangapple go评论100阅读模式
英文:

Bitwise operation && overflow

问题

以下是翻译好的内容:

为什么这两行 Java 代码的结果不同?

int a = 1;
System.out.println(a << 32); //输出:1
System.out.println(a << 31 << 1); //输出:0
英文:

Why the results of this two lines are different in java?

int a = 1;
System.out.println(a &lt;&lt; 32); //output: 1
System.out.println(a &lt;&lt; 31 &lt;&lt; 1); //output: 0

答案1

得分: 2

根据JLS 8 § 15.19

> 如果左操作数的提升类型是int,则只使用右操作数的五个最低位

因此,当移位一个int时,移位距离实际上是右操作数的值对32取模(至少当右操作数为非负数时)。因此,a << 32基本上与a << 0相同,即只是a。但是,a << 31 << 1首先将值为0x00000001a左移31位得到0x80000000,然后再将其左移1位得到0x00000000

英文:

Per JLS 8 § 15.19

> If the promoted type of the left-hand operand is int, then only the
> five lowest-order bits of the right-hand operand are used

When shifting an int the shift distance is thus effectively the value of the right operand mod 32 (at least when the right operand is non-negative). So a &lt;&lt; 32 is basically the same as a &lt;&lt; 0, i.e., just a. But a &lt;&lt; 31 &lt;&lt; 1 first shifts a, whose value is 0x00000001, left by 31 to yield 0x80000000, which is then shifted left by 1 to yield 0x00000000.

huangapple
  • 本文由 发表于 2020年5月30日 11:43:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/62097534.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定