Java
Byte Array
Hex String
Programming
Code Conversion

Java convert a byte array to a hex string?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Converting a byte array to a hexadecimal string is a common operation in Java programming, especially in fields dealing with encryption, compression, or network transmission. This article will discuss various methods to achieve this conversion, along with technical explanations, examples, and a comparison table.

Understanding the Basics

A byte in Java is an 8-bit datatype representing a single numerical value. In contrast, a hexadecimal string (or hex string) is a textual representation where each byte is represented as a two-digit hexadecimal number. Hexadecimal numbering uses base 16, incorporating digits from 0 to 9 and letters from A to F.

Why Convert to Hexadecimal?

Hexadecimal representation is used because it's more human-readable compared to binary, and more compact than displaying data in a binary form which also simplifies debugging and logging of binary data.

Methods of Conversion

Here are three primary methods to convert a byte array to a hex string in Java:

  1. Manual Conversion Using a StringBuilder
  2. Using DatatypeConverter.printHexBinary (Java 8 and below)
  3. Using HexFormat Class in Java 17 onwards

1. Manual Conversion Using StringBuilder

This method involves manually converting each byte to its hexadecimal representation and appending it to a StringBuilder. Here's how you can do it:

java
1public static String bytesToHex(byte[] bytes) {
2    StringBuilder hexString = new StringBuilder();
3    for (byte b : bytes) {
4        String hex = Integer.toHexString(0xFF & b);
5        if (hex.length() == 1) {
6            hexString.append('0'); // Leading zero for values less than 0x10
7        }
8        hexString.append(hex);
9    }
10    return hexString.toString().toUpperCase();
11}

This method masks the byte with 0xFF (255 decimal) to handle negative values correctly, ensuring that the integer conversion handles them as unsigned.

2. Using DatatypeConverter.printHexBinary (Java 8 and below)

The javax.xml.bind.DatatypeConverter class provides a printHexBinary method which directly converts a byte array into a hex string:

java
1import javax.xml.bind.DatatypeConverter;
2
3public static String bytesToHexUsingJAXB(byte[] bytes) {
4    return DatatypeConverter.printHexBinary(bytes);
5}

This method is straightforward and useful, but note that the javax.xml.bind package was removed in Java 11.

3. Using HexFormat Class in Java 17 onwards

Java 17 introduced the HexFormat class, offering a modern and versatile way to convert between bytes and hex strings:

java
1import java.util.HexFormat;
2
3public static String bytesToHexUsingHexFormat(byte[] bytes) {
4    HexFormat hexFormat = HexFormat.of().withUpperCase();
5    return hexFormat.formatHex(bytes);
6}

This approach is not only simple but also part of the standard Java API, ensuring future compatibility and providing options for formatting.

Comparison Table

Here’s a comparison of the three methods described above:

MethodJava Version CompatibilityPerformanceEase of UseFuture Proof
StringBuilder (Manual Conversion)All Java versionsModerateModerateYes
DatatypeConverter.printHexBinaryJava 8 and belowGoodHighNo
HexFormatJava 17 onwardsBestHighYes

Additional Considerations

When converting byte arrays to hex strings, performance and memory usage can become concerns, especially with large data sets. Benchmarks and profiling can be valuable in performance-critical applications to select the optimal method.

Conclusion

While manual conversion offers universal compatibility, newer APIs like HexFormat provide enhanced functionality and simpler syntax. Choosing the right method depends on your specific needs, Java version, and performance requirements. Always consider updating legacy code to newer APIs to leverage improvements in the Java platform.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.