所以我在 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/