Java Shift Operator 和自动升级

标签 java bit-shift

我是一名新手 Java 程序员,正在阅读 Thinking In Java布鲁斯·埃克尔 (Bruce Eckel)。

在第 5 章中,已经讨论了运算符。在谈论移位运算符(<<、>>、>>>)的地方,他说:

If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int. Only the five low-order bits of the right-hand side will be used. This prevents you from shifting more than the number of bits in an int. If you’re operating on a long, you’ll get a long result. Only the six low-order bits of the right-hand side will be used, so you can’t shift more than the number of bits in a long.

我不明白什么意思。特别是大胆的句子。你能澄清一下吗?

最佳答案

我觉得其他答案有点不完整。

int 确实是 32 位,而该语言不允许您移动超过 32 位。遗漏的是,如果您告诉它移位超过 32 位,移位量将取模 32。也就是说,如果 xintx >> 32x >> 0 相同(即只是 x),x >> 33 是等同于x >> 1x >> 66等同于x >> 2等。仅使用低位右参数的 5 位与对参数取模 32 相同(使用数学定义,因此 -1 mod 32 == 31,-2 mod 32 == 30,等等)。

同样,long 是 64 位,这意味着右参数是对 64 取模计算的,这与仅使用右参数的低 6 位相同。

为什么 Java 这样做,我不知道。在我看来,如果它只是让你大量移位,将所有位移出整数并得到 0(除了 >>> 符号扩展,那么它会更一致结果将为 0 或 -1)。它在数学上是一致的,因为对于正的 xyx >> y 总是等于 x/(2 ^y) 被截断为整数,即使 y >= 32。Java 处理 >= 32 或 >= 64 的移位量的方式在任何方面都没有用可以看到。

关于Java Shift Operator 和自动升级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30116352/

相关文章:

c - 使用编译器警告捕获常量1的左移溢出?

go - 1 << 64 - 1 是如何工作的?

java - 除了MVP和MVC还有其他模式吗?

java - 获取 JTextComponent 的 HTMLDocument 中的当前偏移量

java - 在eclipse中编译一个项目,得到war或ear或jar文件

go - 位掩码 int64 中的多个值

c - 使用移位运算符拆分大十进制数

java - Spring框架有一个 "POJO implementation"是什么意思

java - 如何检测 Servlet 内的 ping?

ARGB 到 RGBA 数组转换的 JavaScript 优化版本