Explain Codes LogoExplain Codes Logo

Java integer to byte array

java
bitwise-operations
byte-array-conversion
endianness
Alex KataevbyAlex Kataev·Oct 18, 2024
TLDR

To transform an integer to a byte array in Java, you can utilize the ByteBuffer class as follows:

ByteBuffer.allocate(Integer.SIZE / Byte.SIZE).putInt(123456789).array();

This code allocates ByteBuffer to handle 4 bytes (the size of an integer), inputs the integer with putInt, and retrieves the resulting byte array with array().

Going beyond - alternative solutions

Bitwise shifts

Bitwise shifts and masking can achieve the desired transformation:

int yourInt = 123456789; //Replace 123456789 with your desired integer byte[] byteArr = new byte[4]; for (int i = 0; i < 4; i++) { byteArr[i] = (byte) (yourInt >>> (i * 8)); // Magic happens here! }

Adjust the shift direction to control endianness.

Guava library

Consider Guava's Ints.toByteArray() for a direct, elegant conversion:

byte[] byteArr = Ints.toByteArray(123456789);

This method neatly abstracts away conversion complexities.

Arrays.copyOf()

Combine Arrays.copyOf() with range operations for customized byte array management:

int yourInt = 123456789; byte[] fullSize = ByteBuffer.allocate(8).putInt(yourInt).array(); byte[] byteArr = Arrays.copyOfRange(fullSize, 4, 8); // Last four bytes are kept

This approach diversifies array size management and content control.

Deeper insights

Managing byte order (endianness)

Beware of endianness! Specify ByteOrder when working with byte arrays:

int yourInt = 123456789; ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(ByteOrder.LITTLE_ENDIAN); // Use ByteBuffer.order to set endianness buffer.putInt(yourInt); byte[] byteArr = buffer.array(); // Now bytes are ordered in little-endian

Avoiding Integer.toHexString()

Avoid Integer.toHexString() if you need a real byte array. It provides a String representation, not actual byte values.

The BigInteger illusion

Consider using BigInteger for non-primitive types and larger values:

byte[] byteArr = new BigInteger(String.valueOf(123456789)).toByteArray();

Yet beware - this could introduce padding or sign-related bytes. Interpret with caution.

Traps and tricks

  • Underflow and Overflow: Ensure your values fit within the byte's range. Losing data isn't fun!
  • Immutable ByteBuffers: You can't modify the byte array from a ByteBuffer once it's retrieved via array().
  • Byte Order: Different systems use different endianness. Double-check when writing and reading to avoid headaches.