Explain Codes LogoExplain Codes Logo

Convert integer into byte array (Java)

java
bytebuffer
endianness
bitwise-manipulation
Anton ShumikhinbyAnton Shumikhin·Jul 22, 2024
TLDR

The quickest way to convert an integer to a byte array in Java is to use the ByteBuffer class. Below is a concise sample snippet:

byte[] byteArray = ByteBuffer.allocate(4).putInt(123456).array();

Just like a humble Swiss army knife, this single line of code consists of three powerful operations: creation of a ByteBuffer, writing an integer onto it, and fetching out the byte array.

ByteBuffer: Java's secret byte manipulator

ByteBuffer is a powerful class in Java designed for buffer management and manipulation of bytes. It's like having a byte-level wand for your byte sorcery. To use ByteBuffer, it's important to pre-allocate a space for your byte array using ByteBuffer.allocate().

When dealing with byte ordering, remember that endian-ness matters. Specify it explicitly using ByteBuffer.order():

ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(ByteOrder.BIG_ENDIAN); // or ByteOrder.LITTLE_ENDIAN buffer.putInt(123456); byte[] byteArray = buffer.array();

Did you notice? The ByteBuffer made the ordering pretty straightforward. You definitely won't need to call a Byte Order Whisperer with ByteBuffer. For a profound understanding, don't forget to check the Java's official ByteBuffer documentation.

Manual bit manipulation: Because sometimes, you just want to get your hands dirty

If ByteBuffer feels like an overkill, or you simply enjoy a byte of manual labor, bit manipulation is your answer. Convert an integer to a byte array using bitwise shifts and masks like this:

byte[] byteArray = new byte[4]; int value = 123456; // "Remember, int, bytes are made by stripping you" byteArray[0] = (byte)(value >> 24 & 0xFF); byteArray[1] = (byte)(value >> 16 & 0xFF); byteArray[2] = (byte)(value >> 8 & 0xFF); byteArray[3] = (byte)(value & 0xFF);

Who said coding isn't fun? Performing bitwise manipulation isn't just cool, it's often just as performant as ByteBuffer and offers a deep-dive into the binary operations at the core of your integers.

Make it rain with DataOutputStream

For all the stream enthusiasts out here, DataOutputStream offers custom solutions with style. If you're looking for something more elegant, try writing an integer to a ByteArrayOutputStream:

ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeInt(123456); // "Writing integer - feels like an artist!" dos.flush(); byte[] byteArray = baos.toByteArray();

Streams might be a byte tricky, but that's why they're so much streamy fun. Although it might add some additional overhead, it can be a good fit when dealing with a stream-oriented application.

Libraries: Because everyone needs some external help sometimes

Well, guess what, Guava decided to join the byte-party. It offers the Ints.toByteArray() method for an elegant and optimized conversion:

byte[] byteArray = Ints.toByteArray(123456);

Binary not your primary language? No problem! Libraries like Guava speak it fluently. So, check out Guava's documentation and feel free to explore.

BigInteger: For when integers are just not big enough

BigInteger being the muscle-bound cousin of Integer, provides valueOf() and toByteArray() methods. Attention though, positive integers will get a leading 0x00 byte to showcase their positivity.

byte[] byteArray = BigInteger.valueOf(123456).toByteArray();

If size matters for you, BigInteger will not disappoint, especially when dealing with large numbers or combinations of string-byte conversions.

Visualization

Imagine that an integer is a treasure chest (🏴‍☠️) filled with gold coins. Each piece of gold represents a byte:

Integer Treasure Chest (🏴‍☠️): 2600

To convert this to a byte array, we must unlock the chest and place each gold coin into one of four bags. Each one represents a byte in the byte array:

byte[] byteArray = new byte[4];

So now we have:

Byte Array Bags: [🎒, 🎒, 🎒, 🎒]

Each 🎒 holds a piece of our integer treasure in the form of a byte:

  • 🎒1: Most significant byte (MSB)
  • 🎒4: Least significant byte (LSB)

We've just created a digital treasure map! It's just preserving the big-endian byte order: the order in which our byte pieces should be arranged to keep the treasure's original value.

Watch out for pitfalls and performance dilemmas

Converting an integer to a byte array might be tricky sometimes. Remember, endianness can be a traitor: always better to employ ByteBuffer.order() to remain in control.

If you're digesting the buffer by reading from it after writing to it, don't forget that ByteBuffer.flip() is like the flip of a switch you really need.

For "performance junkies", bitwise operations might outshine ByteBuffer. Beware though, you can lose data when casting directly to a byte!

Also, remind yourself of the memory overhead DataOutputStream may introduce, especially if you're dealing with large volumes of data conversions. The memory beast is real!