英文:
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 << 32); //output: 1
System.out.println(a << 31 << 1); //output: 0
答案1
得分: 2
> 如果左操作数的提升类型是int,则只使用右操作数的五个最低位
因此,当移位一个int
时,移位距离实际上是右操作数的值对32取模(至少当右操作数为非负数时)。因此,a << 32
基本上与a << 0
相同,即只是a
。但是,a << 31 << 1
首先将值为0x00000001
的a
左移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 << 32
is basically the same as a << 0
, i.e., just a
. But a << 31 << 1
first shifts a
, whose value is 0x00000001
, left by 31 to yield 0x80000000
, which is then shifted left by 1 to yield 0x00000000
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论