Java
Byte Array
Hexadecimal
Data Conversion
Programming

How can I convert a byte array to hexadecimal in Java?

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

Introduction

Converting a byte array to a hexadecimal string in Java is a common requirement when dealing with binary data. Hexadecimal representation is convenient for debugging, logging, or displaying bytes in a human-readable format since it condenses each byte into two characters. This article provides a comprehensive guide on how to efficiently accomplish this task using Java, detailing the various approaches and their intricacies.

Understanding Byte Arrays and Hexadecimal

Before delving into code examples, let's clarify what byte arrays and hexadecimal formats are:

  • Byte Array: An array of type byte in Java represents a collection of 8-bit binary data. Each element can hold a value between -128 and 127.
  • Hexadecimal Representation: This is a base-16 numbering system using sixteen distinct symbols, typically 0-9 and A-F, to represent values.

Method 1: Using StringBuilder and Bitwise Operations

The most explicit method to convert a byte array to a hexadecimal string is by using a loop in conjunction with bitwise operations. Here's how it works:

java
1public class ByteArrayToHex {
2    public static String bytesToHex(byte[] bytes) {
3        StringBuilder hexString = new StringBuilder();
4        for (byte b : bytes) {
5            String hex = Integer.toHexString(0xFF & b);
6            if (hex.length() == 1) {
7                hexString.append('0'); // pad with leading zero
8            }
9            hexString.append(hex);
10        }
11        return hexString.toString().toUpperCase();
12    }
13
14    public static void main(String[] args) {
15        byte[] byteArray = new byte[]{(byte) 0x0F, (byte) 0x1A, (byte) 0x2B};
16        System.out.println("Hexadecimal: " + bytesToHex(byteArray));
17    }
18}

Explanation:

  1. Masking with 0xFF: This operation converts the signed byte to a positive integer, effectively zero-filling the leftmost bits.
  2. Padding with Zero: The result of Integer.toHexString() may produce a single character for values less than 16. Padding ensures two-character width for each byte.

Method 2: Using DatatypesConverter (JDK 1.6 to 1.8)

For Java 6 and above, javax.xml.bind.DatatypeConverter offers a simpler solution. However, this class was deprecated in Java 9 and later removed in newer releases.

java
1import javax.xml.bind.DatatypeConverter;
2
3public class ByteArrayToHex {
4    public static String bytesToHex(byte[] bytes) {
5        return DatatypeConverter.printHexBinary(bytes).toUpperCase();
6    }
7
8    public static void main(String[] args) {
9        byte[] byteArray = new byte[]{(byte) 0x0F, (byte) 0x1A, (byte) 0x2B};
10        System.out.println("Hexadecimal: " + bytesToHex(byteArray));
11    }
12}

Explanation:

This approach abstracts the conversion behind a simple method call, providing a convenient yet deprecated solution for specific JDK versions.

Method 3: Using Commons Codec Library

Apache Commons Codec library simplifies the conversion with a built-in utility:

  1. Add the Dependency:
    • For Maven, include:
xml
1    <dependency>
2        <groupId>commons-codec</groupId>
3        <artifactId>commons-codec</artifactId>
4        <version>1.15</version> <!-- or the latest version -->
5    </dependency>
  1. Converting Byte Array to Hex:
java
1    import org.apache.commons.codec.binary.Hex;
2
3    public class ByteArrayToHex {
4        public static String bytesToHex(byte[] bytes) {
5            return Hex.encodeHexString(bytes).toUpperCase();
6        }
7
8        public static void main(String[] args) {
9            byte[] byteArray = new byte[]{(byte) 0x0F, (byte) 0x1A, (byte) 0x2B};
10            System.out.println("Hexadecimal: " + bytesToHex(byteArray));
11        }
12    }

Explanation:

This method expedites development by leveraging a robust external library widely used for encoding and decoding operations.

Performance Considerations

Each method has its pros and cons:

  • Manual Conversion offers full control and understanding, and it's lightweight but can be verbose.
  • DatatypeConverter provides ease of use but lacks support in newer Java versions due to deprecation.
  • Commons Codec gives a neat and reliable solution at the cost of an external dependency, especially beneficial in projects already using this library.

Key Points Summary

MethodProsCons
Manually using StringBuilder and Bitwise OperationsFull control, No dependenciesVerbose, Manual padding needed
DatatypeConverterSimple, Built-in (for JDK <= 1.8)Deprecated post JDK 8
Commons Codec (Apache)Simple, ReliableExternal dependency required

Conclusion

Converting a byte array to a hexadecimal string in Java can be accomplished in several ways, each with its own use cases and constraints. Depending on your specific requirements and project setup (like existing dependencies or Java version), you can choose the method that best fits your needs. It's always prudent to consider both performance implications and future maintainability when selecting an approach.


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.