我是一名新手 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。也就是说,如果 x
是 int
,x >> 32
与 x >> 0
相同(即只是 x
),x >> 33
是等同于x >> 1
,x >> 66
等同于x >> 2
等。仅使用低位右参数的 5 位与对参数取模 32 相同(使用数学定义,因此 -1 mod 32 == 31,-2 mod 32 == 30,等等)。
同样,long
是 64 位,这意味着右参数是对 64 取模计算的,这与仅使用右参数的低 6 位相同。
为什么 Java 这样做,我不知道。在我看来,如果它只是让你大量移位,将所有位移出整数并得到 0(除了 >>>
符号扩展,那么它会更一致结果将为 0 或 -1)。它在数学上是一致的,因为对于正的 x
和 y
,x >> y
总是等于 x/(2 ^y)
被截断为整数,即使 y
>= 32。Java 处理 >= 32 或 >= 64 的移位量的方式在任何方面都没有用可以看到。
关于Java Shift Operator 和自动升级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30116352/