Java 语言规范中的位移运算符描述

Bitshift operators description in Java language specification

在 JLS8 中指定 §JLS-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 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.

这个加粗的说法我不是很清楚。非常感谢一个例子。

它 Java 利用 C 和 C++ 世界的编译器优化。对于 32 位 int,使用大于或等于 31 的移位参数会将结果值设置为 0,以表示正值 int。 (对于否定论点,C 和 C++ 中关于移位的行为是 实现定义)。

而在 C 和 C++ 中,实际上对 32 位 int 使用大于 31 的值实际上是 未定义的行为,Java bods实际上已经明确定义了行为,并简单地用参数模 32 执行移位(这是大多数 C 和 C++ 编译器实际做的)。您引用的 JLS 片段中明确提到了此方法。

提取一个数的最低五位相当于对该数取模 32。