>> 在我的测试中与 >> 没有区别。 -128 >> 4 = -8 正如预期的那样,但是-6ren">
gpt4 book ai didi

Java 的无符号位移右 (>>>) 是有符号位移

转载 作者:行者123 更新时间:2023-12-03 23:13:37 24 4
gpt4 key购买 nike

我正在尝试右移以将某些位与字节隔离,所以我想要一个无符号移位,据我所知,"new"位应该为零。但是,我发现 >>> 在我的测试中与 >> 没有区别。 -128 >> 4 = -8 正如预期的那样,但是 -128 >>> 4 应该是 8 但我仍然得到 -8。

byte data = (byte)-128;
System.out.println((byte)(data >>> 4));
System.out.println((byte)(data >> 4));

感谢您的帮助。

最佳答案

无符号右移运算符确实在这段代码中进行了无符号右移;它只是因为来自 byte 的隐式转换而被隐藏至int .说 Java 语言规范 (§15.19):

The operators << (left shift), >> (signed right shift), and >>> (unsigned right shift) are called the shift operators. The left-hand operand of a shift operator is the value to be shifted; the right-hand operand specifies the shift distance. [...] Unary numeric promotion (§5.6.1) is performed on each operand separately.

一元数字提升表示(§5.6.1):

[...] if the operand is of compile-time type byte, short, or char, it is promoted to a value of type int by a widening primitive conversion (§5.1.2).

所以你的代码被评估如下:

  • byte值(value) -128这是 >>> 的左操作数晋升为int值(value) -128 ,即 0b11111111111111111111111110000000二进制。
  • 无符号右移是在这个 int 上完成的。值,结果为 268435448二进制是0b00001111111111111111111111111000 .请注意,最左边的四位为零,正如您对无符号右移所期望的那样。
  • 此结果随后显式转换为 (byte) , 给出结果 -8 .

使用 REPL:

> byte b = -128;
> int shifted = b >>> 4;
> shifted
268435448
> (byte) shifted
-8

对于你想要的行为,你可以使用& 0xFFbyte 进行“无符号”转换至int :

> ((b & 0xFF) >>> 4)
8

关于Java 的无符号位移右 (>>>) 是有符号位移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60270884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com