签名字节上的无符号右移产生错误

时间:2016-08-13 10:03:39

标签: java bit-shift unsigned

我正在经历一些奇怪的无符号右移操作,当尝试在Java 8上的硬编码数据而非硬编码数据上执行时会产生错误的结果。

我正在尝试对带符号的字节0xBF执行无符号右移。如果我只是将带符号的字节分配给变量,然后使用该变量执行无符号右移操作,我最终得到0xDF。如果我将0xBF硬编码为无符号右移操作,我得到0x5F

byte originalByte = (byte) 0xBF;
System.out.println("Original Data: " + toHexString(new byte[]{originalByte}));

byte rotatedByte = (byte) (originalByte >>> 1);
System.out.println("Rotated Data: " + toHexString(new byte[]{rotatedByte}));

byte signRemoved = (byte) (0xBF >>> 1);
System.out.println("Sign Removed Data: " + toHexString(new byte[]{signRemoved}));

上述Java调用的输出。

Original Data: BF
Rotated Data: DF
Sign Removed Data: 5F

我该如何解决上述问题?

1 个答案:

答案 0 :(得分:0)

如果是旋转字节,则表示您正在对字节类型进行操作。在signRemoved的情况下,您正在对int类型执行操作,并在操作完成后将其转换为byte。因此结果不同。

int i = 0xBF; // this is int and the value is 191
byte b = (byte) 0xBF; // this is byte and value is -65 

int i2 = (i >>> 1) //here the operation is done on int result is 95
byte b2 = (byte) i2 // result stays 95

int i3 = b >>> 1 // here b is first promoted to int (-65) then  after right shift it becomes 2147483615
byte b3 = (byte) i3 // -33
相关问题