-1 除以 2 怎么会得到 -1? (按位运算 >>)

How can -1 divided by 2 result in -1? (bitwise operation >>)

我很惊讶地看到 -1 除以 2 使用按位运算结果 -1。

我原以为会返回 0。

就像你用 1 或 -1 除以 2 一样,小数部分被去掉,我们得到零。 这可能与Two's complement有关,但只是猜测和我不完全理解的猜测。

有人可以解释一下吗?

-1 >> 1 = -1

-1 / 2 = 0

 public class JavaFiddle
  {
    public static void main(String[] args)
    {
      System.out.println(-1 >> 1);
      System.out.println(-1 / 2);
    }
  }

java 中的负数使用称为 2's complement 的符号表示。如果我们假设有符号整数的大小是 8。你可以这样想 2 的补码

2 will be  00000010
1 will be  00000001
0 will be  00000000
-1 will be 11111111 (Count in reverse from max)
-2 will be 11111110
-3 will be 11111101

(实际上在java中int的大小是4个字节)

>> 这是有符号的按位右移运算符。根据 documentation 它在最左边的位置为正数填充 0,对于负数它将用 1 填充相同的位置。

这意味着将 -1 移动任意次数只会得到 -1。

11111111 >> 1 = 11111111

这是因为 Non-equivalence of arithmetic right shift and division 负数除以 2 的含义,右移不应在所有情况下都被视为相等