Java int to byte[] Conversion: Little-Endian and Big-Endian Examples
When converting an int to a byte[] in Java, the key difference is the byte order. In practice, this usually comes down to whether the low byte is stored first or the high byte is stored first.
Convert int to byte[] in little-endian order
In little-endian format, the least significant byte comes first:
public static byte[] toLH(int n) {
byte[] b = new byte[4];
b[0] = (byte) (n & 0xff);
b[1] = (byte) (n >> 8 & 0xff);
b[2] = (byte) (n >> 16 & 0xff);
b[3] = (byte) (n >> 24 & 0xff);
return b;
}
Here, the integer is split into 4 bytes, from low to high, and placed into the array in order.
Convert int to byte[] in big-endian order
In big-endian format, the most significant byte is placed first:
public static byte[] toHH(int n) {
byte[] b = new byte[4];
b[3] = (byte) (n & 0xff);
b[2] = (byte) (n >> 8 & 0xff);
b[1] = (byte) (n >> 16 & 0xff);
b[0] = (byte) (n >> 24 & 0xff);
return b;
}
This version writes the same 4 bytes in the opposite order, so the high byte ends up at index 0.
Convert byte[] to int in little-endian order
If the byte array stores the low byte first, each byte should be shifted according to its position:
public int toInt(byte[] b){
int res = 0;
for(int i=0;i<b.length;i++){
res += (b[i] & 0xff) << (i*8);
}
return res;
}
The expression (b[i] & 0xff) avoids sign extension when a byte is promoted to int. Then each byte is moved back to its proper bit position with << (i*8).
Convert byte[] to int in big-endian order
For a byte array with the high byte first, the shift position is reversed:
public static int toInt(byte[] b){
int res = 0;
for(int i=0;i<b.length;i++){
res += (b[i] & 0xff) << ((3-i)*8);
}
return res;
}
In this case, b[0] is treated as the highest byte, so it is shifted by 24 bits, while later bytes are shifted less.
The main thing to watch is endianness. As long as the byte order used when writing matches the byte order used when reading, the conversion between int and byte[] will work correctly.