1 回答
TA贡献1818条经验 获得超11个赞
首先,您需要了解符号扩展。您需要将每个字节视为无符号值。
long v = 0;
byte q = -2; // unsigned value of 254
v = v + q;
System.out.println(v); // prints -2 which is not what you want.
v = 0;
v = v + (q & 0xFF); // mask off sign extension from q.
System.out.println(v); // prints 254 which is correct.
这是一种方法。
long val = 0;
byte[] bytes = { -1, 12, 99, -121, -3, 123
};
for (int i = 0; i < bytes.length; i++) {
// shift the val left by 8 bits first.
// then add b. You need to mask it with 0xFF to
// eliminate sign extension to a long which will
// result in an incorrect conversion.
val = (val << 8) | ((i == 0 ? bytes[i]
: bytes[i] & 0xFF));
}
System.out.println(val);
添加回答
举报