Explain Codes LogoExplain Codes Logo

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

java
hex-conversion
byte-array
string-conversion
Nikita BarsukovbyNikita Barsukov·Oct 19, 2024
TLDR

Let's leverage BigInteger and String.format to transform a byte array into a hex string, leading zeros intact:

byte[] bytes = {0, 15, 5}; // A sunny day for byte arrays! String hex = String.format("%0" + (bytes.length * 2) + "x", new BigInteger(1, bytes)); System.out.println(hex); // Outputs: "000f05", looking good!

This approach makes sure that leading zeros feel loved and never get ignored.

Option with Flair: Apache Commons Codec

A connoisseur of third-party libraries? Apache Commons Codec is your go-to. First, add its magic in your POM file:

<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.15</version> <!-- Everything's classy with 1.15 --> </dependency>

Then, just call upon the mighty Hex.encodeHexString to do your bidding:

import org.apache.commons.codec.binary.Hex; byte[] bytes = {0, 15, 5}; // Array parked and ready String hex = Hex.encodeHexString(bytes); System.out.println(hex); // Outputs: "000f05", oh yeah!

Home-made Hex converter: For DIY lovers

For the star bakers who prefer home-cooked code, here's a loop with bitwise operations:

byte[] bytes = {0, 15, 5}; // Huddle up, bytes, we're going in! StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02x", b)); } System.out.println(sb.toString()); // Outputs: "000f05", yum-yum!

This manual method is your playground. Remix and season it to your tastes!

High-stakes scenarios: Byte array on an epic scale

When you're battling with giant byte arrays, every optimization makes a difference:

Halving time, doubling style with StringBuilder and hex characters

byte[] bytes = {0, 15, 5}; StringBuilder hexBuilder = new StringBuilder(bytes.length * 2); // Pre-allocated capacity, knock-knock memory leak, who's there! final char[] hexArray = "0123456789ABCDEF".toCharArray(); for (byte b: bytes) { int v = b & 0xFF; hexBuilder.append(hexArray[v >>> 4]); hexBuilder.append(hexArray[v & 0x0F]); } String hex = hexBuilder.toString(); // Full-throttle conversion!

In the high-performance lane

To make it in time for dinner:

  • Ditch new object creation in loops.
  • Pre-size your StringBuilder, because wisdom is knowing when to book your table.
  • Use bitwise shift instead of modulo and division - faster than a speeding bullet!

Dark alley scenarios: When byte order matters

If you're playing in the Major League of data accuracy, beware the byte order wolf:

  • Get your endianness straight: Big endian or little endian, it's reading order not a burger!
  • If endianness rears its head, quickly bring out your ByteBuffer shield.

A touch of modern with Java 8+

Java 8, anyone? The dashing DatatypeConverter class is here to rescue:

import javax.xml.bind.DatatypeConverter; byte[] bytes = {0, 15, 5}; String hex = DatatypeConverter.printHexBinary(bytes); // Instant glamour!

Don't forget, post-Java 9, this class is in the Java witness protection program:

--add-modules java.xml.bind

Pro tips: The golden nuggets

Keep it clean, keep it consistent

Ensure consistency:

  • For case-sensitive environments, String.format with "X" gives uppercase and "x" outputs lowercase hex.
  • Zero-padding: Length matters, especially when on a strict fixed format diet.

Troubleshooting 101

  • Input size: Is your input byte array sized for the runway or sitting at home in pajamas?
  • Data corruption: Always perform a round-trip test (hex string to byte array and back) to prevent "Lost in Translation" scenarios.