Java 按位运算符 <<

标签 java bit-manipulation bit-shift

<分区>

有人可以解释为什么以下按位表达式返回不同的结果吗:

System.out.println((-1<<31)<<1);   // it prints 0
System.out.println(-1<<32);        // it prints -1

最佳答案

-1<<32相当于-1<<0 ,即无操作。原因是移位距离(32)0x1f 进行与运算和 32 & 0x1f为 0。

这是在 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 按位运算符 <<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36304960/

相关文章:

Java JLabel 不会更新

java - URL 包含空格的 HttpURLConnection

c++ - unsigned int 零的位表示

C 位移位 : right operand considered for implicit type-conversion?

kotlin - Kotlin `shl`无法正常工作

java - 如何在 Clojure 中动态查找静态类成员?

java - spring bean怎么可能有工厂方法但没有工厂?

c++ - z 顺序曲线中的下一次迭代

c - "Marking"C 中的指针与 "attributes"

bit-manipulation - 位操作的时间复杂度