1

我正在尝试转换-101为字节数组,然后将字节数组转换回-101. 我下面的方法适用于正值,但不适用于负值。你能建议我做错了什么吗?-101byteArrayToInt方法返回,而不是65435。谢谢!

/**
 * 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
}
4

1 回答 1

3

您需要签名扩展您的号码。如果您还没有,您应该阅读带符号二进制数的二进制补码表示。

-101作为 32 位整数的数字是0xFFFFFF9B十六进制的。您将其转换为 2 个字节的字节数组。就这样离开了0xFF9B。现在,当您将其转换回时,您将其转换为 32 位整数,结果为0x0000FF9B, 或65435十进制。

您应该检查字节数组中的最高位并基于此进行符号扩展。一个简单的方法是从 value=-1最高位是否设置开始,如果没有设置则默认为value=0

编辑:检查最高位的一种简单方法是检查高位字节是否为负。

于 2012-08-16T06:57:40.967 回答