简体   繁体   English

字节数组到*签名* Int

[英]Byte Array to *Signed* Int

I'm trying to convert -101 to a byte array and then convert the byte array back to -101 . 我正在尝试将-101转换为字节数组,然后将字节数组转换回-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 . 而不是-101byteArrayToInt方法返回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. 如果您还没有,则应阅读已签名二进制数的二进制补码表示。

The number -101 as a 32-bit integer is 0xFFFFFF9B in hex. 作为32位整数的数字-101是十六进制的0xFFFFFF9B You convert it to a byte array of 2 bytes. 您将其转换为2个字节的字节数组。 That leaves just 0xFF9B . 0xFF9B Now, when you convert it back you convert it into a 32-bit integer and the result is 0x0000FF9B , or 65435 in decimal. 现在,当您将其转换回来时,将其转换为32位整数,结果为0x0000FF9B或十进制65435

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. 一个简单的方法是,如果设置了最高位,则以value=-1开始,如果不是,则默认为value=0

Edit: An easy way to check the highest-order bit is to check if the high-order-byte is negative. 编辑:检查最高位的简单方法是检查高位字节是否为负。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM