gpt4 book ai didi

java - Java 移位操作实现背后的逻辑

转载 作者:行者123 更新时间:2023-12-01 16:48:27 26 4
gpt4 key购买 nike

根据 JLS 第 15.19 条:

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

我们可以在 C# 中找到同样的东西。在 Python 中,它将是 6 位而不是 5 位,但逻辑保持不变。

其背后的原因是什么?对我来说,拥有以下内容会更自然:

x << 32 = 0 

而不是

x << 32 = x

此外,对于负整数使用移位运算永远不会得到 0。

最佳答案

摘自 Joshua Bloch 和 Neal Gafter 所著的《Java Puzzlers: Traps, Pitfalls and Corner Cases》一书:

Language designers should perhaps consider restricting shift distances to the range from 0 to the type size in bits and changing the semantics of shifting a value by the type size to return 0. Although this would avoid the confusion …, it could have negative performance consequences; Java's semantics for the shift operators are those of the shift instructions on many processors.

关于java - Java 移位操作实现背后的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61736189/

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