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