为什么我的 Java short 被无符号右移填满 1?

Why is my Java short getting filled with 1s with an unsigned right shift?

当我执行如下无符号右移时:

short value = (short)0b1111111111100000;
System.out.println(wordToString(value));
value >>>= 5;

我得到 1111111111111111。 因此,值向右移动,但填充了 1,这似乎与 >>

的行为相同

但是,无论符号如何,我都希望它用 0 填充,结果如下: 0000011111111111

这里有一个相关的 REPL 来玩我的代码:https://repl.it/@spmcbride1201/shift-rotate

您得到的行为与以下事实有关:在应用移位操作之前 shorts 被提升为 ints。事实上,如果将移位运算符的结果分配给 int 变量,您会得到预期的结果:

  public static void main(String[] args) {

    short value = (short)0b1111111111100000;
    System.out.println(value); //-32, which is the given number
    int result = value >>> 5;
    System.out.println(result); //134217727, which is 00000111111111111111111111111111

  }

如果将结果分配给 short,则只会得到低位。

这是因为字节码语言并不真正处理任何小于 int 的类型。