java - 左移丢失的信息是否存储在Java中的某个地方?

标签 java bit-manipulation bitwise-operators bit bit-shift

所以我在 Java 中尝试左移,但发现了一些我不明白的东西。下面的代码对此进行了描述。

int x = -1 << 31;
System.out.print(Integer.toBinaryString(-1) + " -1\n");
System.out.print(Integer.toBinaryString(x) + " " + x + "\n");

// output
11111111111111111111111111111111 -1
10000000000000000000000000000000 -2147483648

所以我只是去掉了整数-1左边的31个1,结果就是我所期望的。然而,当我尝试左移 1 个位置后,我得到的不是 0,而是 -1。

int x = -1 << 32; // one more left shift
System.out.print(Integer.toBinaryString(-1) + " -1\n");
System.out.print(Integer.toBinaryString(x) + " " + x + "\n");

// output
11111111111111111111111111111111 -1
11111111111111111111111111111111 -1

然后我尝试将最小整数值 -2147483648 直接左移 1。结果得到了预期值 0。

System.out.println(-2147483648 << 1); // the output is 0

有人可以向我解释一下幕后发生了什么吗?

最佳答案

这是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.

所以-1 << 32-1 << 0 相同,解释你的结果。

关于java - 左移丢失的信息是否存储在Java中的某个地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50555853/

相关文章:

javascript - Array.prototype.find (polyfill) 中运算符>>>(零填充右移)的用法

java - 使用向导插件

java - SQL 准备语句;我做对了吗?

c - 仅使用按位函数求出表示 2 的补码需要多少位

c++ - 最快的位板换位 (5x5)

c - 以下语句中的单个 & 是什么意思?

java - 在拦截器中抛出 ConstraintViolationException

java - 使此行从第 9 列 Sonar 违规修复开始(源代码应一致缩进)

c++ - 确定数的幂

c - 在字符数组中寻找特定的一对位 '10' 或 '01'