2012-08-16 2 views
1

-101을 바이트 배열로 변환하고 바이트 배열을 다시 -101으로 변환하려고합니다. 내 메소드는 양수 값에서는 작동하지만 음수 값에서는 작동하지 않습니다. 내가 뭘 잘못하고 있는지 제안 해 줄 수 있니? -101 대신 byteArrayToInt 메서드는 65435을 반환합니다. 감사!* Signed * 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을 읽어야합니다.

숫자가 -101 인 32 비트 정수는 0xFFFFFF9B입니다. 이를 2 바이트의 바이트 배열로 변환합니다. 그저 0xFF9B으로 남습니다. 이제 다시 변환 할 때 32 비트 정수로 변환하면 결과는 0x0000FF9B 또는 65435 10 진수입니다.

바이트 배열의 최상위 비트를 확인하고 그에 따라 부호 확장을 수행해야합니다. 가장 쉬운 방법은 최상위 비트가 설정된 경우 value=-1으로 시작하는 것이고 그렇지 않은 경우 기본값은 value=0입니다.

편집 : 비트가 상위 바이트가 부의 경우 확인하는 것입니다 가장 높은 순서를 확인하는 쉬운 방법.