字节偏移反向操作 [英] Byte shift inverse operation
本文介绍了字节偏移反向操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的code
byte[] b = new byte[]{-33,-4,20,30};
System.err.println(Arrays.toString(b));
int x = (b[0] << 24) + (b[1] << 16) + (b[2] << 8) + b[3];
b = new byte[]{(byte)(x >> 24), (byte)(x >> 16), (byte)(x >> 8), (byte)(x)};
System.err.println(Arrays.toString(b));
输出:
[-33, -4, 20, 30]
[-34, -4, 20, 30]
我想不通为什么这个操作并不INVERS。
I cannot figure out why this operations are not invers.
推荐答案
您的问题是多余的符号扩展。
Your problem is unwanted sign extension.
具体而言, B [1]
是 -4
或 0xFC有
这是符号扩展为 0xfffffffc
然后左转向 0xfffc0000
。此具有由1递减最显著字节的效果。
Specifically, b[1]
is -4
, or 0xfc
which is sign-extended to 0xfffffffc
then left-shifted to 0xfffc0000
. This has the effect of decrementing the most-significant byte by 1.
尝试:
int x = ((b[0] & 0xff) << 24) +
((b[1] & 0xff) << 16) +
((b[2] & 0xff) << 8) +
(b[3] & 0xff);
这篇关于字节偏移反向操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文