2012-08-16 60 views
1

我试图将-101转换为字节数组,然后将字节数组转换回-101。下面我的方法适用于正值,但不适用于负值。你能提出我做错了什么吗?而不是-101byteArrayToInt方法返回65435。谢谢!字节数组* *签名* Int

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

回答

3

您需要签名扩展您的电话号码。如果您还没有,请阅读two's complement表示符号的二进制数字。

作为32位整数的数字-101是十六进制的0xFFFFFF9B。您将其转换为2个字节的字节数组。那只剩下0xFF9B。现在,当您将其转换回来时,将其转换为32位整数,结果为十进制的0x0000FF9B65435

您应该检查您的字节数组中的最高位,并根据该位进行符号扩展。如果设置了最高位,最简单的方法是从value=-1开始,如果不是,则默认为value=0

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