字节数组到*签名* Int [英] Byte Array to *Signed* Int
问题描述
我正在尝试将 -101
转换为字节数组,然后将字节数组转换回 -101
。我的方法适用于正值,但不适用于负值。你能说出我做错了什么吗?而不是 -101
, byteArrayToInt
方法返回 65435
。谢谢!
I'm trying to convert -101
to a byte array and then convert the byte array back to -101
. My methods below work for positive values but not for negative values. Can you suggest what I'm doing wrong? Instead of -101
, the byteArrayToInt
method returns 65435
. Thanks!
/**
* Converts a <code>byte</code> array to a 32-bit <code>int</code>.
*
* @param array The <code>byte</code> array to convert.
* @return The 32-bit <code>int</code> value.
*/
public static int byteArrayToInt(byte[] array) {
ValidationUtils.checkNull(array);
int value = 0;
for (int i = 0; i < array.length; i++) {
int shift = (array.length - 1 - i) * 8;
value = value | (array[i] & 0xFF) << shift;
}
return value;
}
/**
* Converts a 32-bit <code>int</code> to a <code>byte</code> array.
*
* @param value The 32-bit <code>int</code> to convert.
* @return The <code>byte</code> array.
*/
public static byte[] intToByteArray(int value, int size) {
byte[] bytes = new byte[size];
for (int index = 0; index < bytes.length; index++) {
bytes[index] = (byte) (value >>> (8 * (size - index - 1)));
}
return bytes;
}
/**
* Tests the utility methods in this class.
*
* @param args None.
*/
public static void main(String... args) {
System.out.println(byteArrayToInt(intToByteArray(32, 2)) == 32); // true
System.out.println(byteArrayToInt(intToByteArray(64, 4)) == 64); // true
System.out.println(byteArrayToInt(intToByteArray(-101, 2)) == -101); // false
System.out.println(byteArrayToInt(intToByteArray(-101, 4)) == -101); // true
}
推荐答案
你需要签名 - 扩展您的号码。如果你还没有,你应该阅读有关签名二进制数的二重补充表示。
You need to sign-extend your number. If you haven't already, you should read up on two's complement representation for signed binary numbers.
作为32位整数的数字 -101
是 0xFFFFFF9B
十六进制。您将其转换为2个字节的字节数组。这只留下 0xFF9B
。现在,当您将其转换回来时,将其转换为32位整数,结果为 0x0000FF9B
,或 65435
十进制。
The number -101
as a 32-bit integer is 0xFFFFFF9B
in hex. You convert it to a byte array of 2 bytes. That leaves just 0xFF9B
. Now, when you convert it back you convert it into a 32-bit integer and the result is 0x0000FF9B
, or 65435
in decimal.
您应该检查字节数组中的最高位并根据该位进行符号扩展。一个简单的方法是从值= -1
开始,如果设置了最高位并默认为 value = 0
如果不是。
You should check the highest-order bit in your byte array and sign extend based on that. A simple way to do it would be to start with value=-1
if the highest-order bit is set and default to value=0
if it isn't.
编辑: 检查最高价的简单方法 - order位是检查高位字节是否为负。
An easy way to check the highest-order bit is to check if the high-order-byte is negative.
这篇关于字节数组到*签名* Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!