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



当我执行无符号的右移时,如下所示:

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的类型。

最新更新