我正在尝试理解轮类运算符的概念, 我正在测试以下代码:
15 >> 2;
- 15 >> 2
第一个语句的结果是 3,即 15/4=3 但第二条语句的结果是-4。
我知道-15的二进制是11110001,当我们向右移动2时,我们得到11111100,这是-4。但我不明白为什么结果与简单除法不同 -15/4= -3 而不是 -4?
请指导我为什么会发生这种情况?
最佳答案
移位运算符通过取整而不是截断来删除任何数学分数。 JLS, Section 15.19 ,状态:
The value of
n >> s
isn
right-shifteds
bit positions with sign-extension. The resulting value isfloor(n / 2<sup>s</sup>)
. For non-negative values ofn
, this is equivalent to truncating integer division, as computed by the integer division operator/
, by two to the powers
.
地板-3.75
是 -4
而截断会产生 -3
.
当值右移时,位会丢失,因为它们移出了值的“末尾”。这是负责楼层操作的。
-15: 11110001
-4: 11111100 // The rightmost 1 bit above is lost, resulting in what looks like the floor function.
关于java - 为什么移位运算符>>中的负数结果与正常除法不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54812761/