Explain Codes LogoExplain Codes Logo

How to convert a byte array to a hex string in Java?

java
byte-array
hex-string
performance
Anton ShumikhinbyAnton Shumikhin·Aug 4, 2024
TLDR

In need of a swift solution? You can convert a byte array into a hex string in one line with the toHexString method from the BigInteger class:

import java.math.BigInteger; byte[] bytes = {10, 2, 15, -120}; // Your byte array String hexString = new BigInteger(1, bytes).toString(16); System.out.println(hexString); // Prints your sleek hex string

This is a neat and self-sufficient solution, independent of any external dependencies.

Optimal performance methods

Got a need... a need for speed and dealing with a large quantity of bytes? A custom method using bitwise operations and a char array is your ticket for a fast ride:

public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; char[] hexArray = "0123456789ABCDEF".toCharArray(); for (int i = 0; i < bytes.length; i++) { int v = bytes[i] & 0xFF; // Who needs WiFi when we've got 0xFF! hexChars[i * 2] = hexArray[v >>> 4]; // Willy Wonka's nibble factory hexChars[i * 2 + 1] = hexArray[v & 0x0F]; // And the leftovers go here! } return new String(hexChars); }

This way, & 0xFF masks the pesky sign bit during the byte-to-int transformation. Using >>> and & 0x0F deconstructs the nibbles (4 bits) of a byte for individual hex character mapping.

Library support

Maybe your project is best pals with certain libraries – you could use their byte-to-hex methods to save some sweat:

  • Apache Commons Codec: Run Hex.encodeHexString(bytes) for a straight path to hex nirvana.
  • Google Guava: BaseEncoding.base16().encode(bytes) is like Guava's secret handshake.
  • Bouncy Castle: Their Hex class hides lots of surprise utilities behind its castle walls.

Remember, each library packs its own performance characteristics and additional treats, so pick the one that dances well with your project requirements and dependencies.

Consider benchmarking

If you're unsure which method to boogie with, try some benchmarking. Comparing the performance of your methods using a tool like JMH can offer surprising revelations. Hint: Iterating over bytes is often crowned king in micro-benchmarks.

Additional considerations

Java 9 and above

For the thrill-seekers using Java 9 or above, harness the power of compact strings. They decrease your memory footprint and allow for optimized String handling.

Charset awareness

Here's a hot tip: when dealing with hex strings, the StandardCharsets.US_ASCII is your best buddy.

Precision in formatting

Kick those hard-coded magic numbers to the curb. Format with precision using %02X to guarantee a consistent width and zero-padding for your hex values.

Memory optimization

Allocating StringBuilder? Set the capacity to 2 * byteArray.length. You'll be sailing smooth waters with optimized memory usage.