Question
What is the correct way to convert between byte arrays and integers in Java?
public static void main(String[] args) {
int a = 123;
byte[] aBytes = intToByteArray(a);
int a2 = byteArrayToInt(aBytes);
System.out.println(a); // prints '123'
System.out.println(aBytes); // prints '[B@459189e1'
System.out.println(a2); // prints '123'
System.out.println(intToByteArray(a2)); // prints '[B@459189e1'
}
Answer
In Java, converting integers to byte arrays and back can lead to discrepancies if not handled correctly. This guide provides a detailed explanation of how to perform this conversion accurately using custom functions, as well as common pitfalls and their solutions.
public static int byteArrayToInt(byte[] b) {
int value = 0;
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
value += (b[i] & 0x000000FF) << shift;
}
return value;
}
public static byte[] intToByteArray(int a) {
byte[] ret = new byte[4];
ret[0] = (byte) (a & 0xFF);
ret[1] = (byte) ((a >> 8) & 0xFF);
ret[2] = (byte) ((a >> 16) & 0xFF);
ret[3] = (byte) ((a >> 24) & 0xFF);
return ret;
}
Causes
- The byte array representation may not be interpreted correctly when converting back to an integer if the order of bytes is not handled appropriately.
- Byte data type is signed in Java. When dealing with larger integers, this can cause unexpected results due to sign extension.
Solutions
- Ensure that you are interpreting the byte array in the same order that it was created.
- Use appropriate data size to avoid overflow and ensure the correct transformation from byte array to int.
Common Mistakes
Mistake: Not checking the size of the byte array before conversion.
Solution: Ensure that your byte array is exactly 4 bytes long before attempting to convert it to an integer.
Mistake: Assuming the byte order is the same during conversion.
Solution: Be consistent with your byte order (endianness) when converting both ways.
Helpers
- Java byte array to int
- int to byte array Java
- Java byte array conversion
- Java integer conversion
- convert int to byte array
- convert byte array to int in Java