gpt4 book ai didi

java - 在 Java 中,当使用移位时,为什么 1 << 32 != 1 << 31 << 1?

转载 作者:太空狗 更新时间:2023-10-29 22:53:33 26 4
gpt4 key购买 nike

int a = 1 << 32;
int b = 1 << 31 << 1;

为什么 a == 1b 如我所料为 0。

最佳答案

所有移位都对整数进行 mod 32,对 long 进行 mod 64。

来自 section 15.19 of the spec :

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.

If the promoted type of the left-hand operand is long, then only the six 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 0x3f. The shift distance actually used is therefore always in the range 0 to 63, inclusive.

至于为什么语言是这样设计的——我不知道,但 C# 有相同的设计决策。以下是带注释的 ECMA C# 规范的内容:

C# deliberately keeps implementation-defined behaviors to a miinimum. They are accepted only when the performance impact of forcing uniform behavior would be excessive (such as for some floating-point precision issues). Hence, the size of each integral type is precisely specified, and the character set is fixed to Unicode.

For shift operations, too, uniform behavior is specified. It can be achieved using a single extra instruction (& 0x1F or & 0x3F) that incurs only a tiny cost on modern processors, especially since it does not reference memory. Unlike for floating-point operations, the difference in shift behavior would be dramatic if left to the whim of the processors; rather than a small difference in precision, completely different integral results would be produced.

In making this decision the committe studied reference materials for a number of different processor architectures. There is little consistency in the behavior for shift counts outside the range -32..+32 for 32-bit operands, and respectively -64..+64 for 64-bit operands.

(然后是一些示例的列表。)

这对我来说似乎是一个完全合理的解释。一致性绝对重要,如果不可能在某些系统上以高效的方式实现不同一致的行为,我认为这是一个合理的解决方案。

关于java - 在 Java 中,当使用移位时,为什么 1 << 32 != 1 << 31 << 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/702607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com