Java Convert Byte Array to Hex String

Tags: HexUtils

In this Java tutorial, we learn how to implement a Java utility method to convert a byte array into a hex String in Java programming language.

How to convert byte array to hex String in Java

In this first step, create a new Java class named HexUtils, and a new static method named toHex(byte[] data) with the following steps to convert byte array to hex String:

  • Initialize a StringBuilder instance.
  • Loop through the byte array, each item use the Integer.toHexString(int i) method to convert byte value to hex String
  • Append the hex String of each byte to the result StringBuilder.
  • Return the hex String result from StringBuilder using the StringBuilder.toString().toLowerCase() method.

HexUtils.java

public class HexUtils {

    /**
     * This method to convert byte array to a hex String
     * @param data array of bytes
     * @return hex String
     */
    public static String toHex(byte[] data) {
        StringBuilder stringBuilder = new StringBuilder();
        for (byte item : data) {
            String hexValue = Integer.toHexString(item);
            if(hexValue.length() == 1) {
                stringBuilder.append("0");
            } else if (hexValue.length() == 8) {
                hexValue = hexValue.substring(6);
            }
            stringBuilder.append(hexValue);
        }
        return stringBuilder.toString().toLowerCase();
    }
}

In the following example Java code, we learn how to use the above HexUtils.toHex(byte[] data) static method above in Java program.

HexUtilsToHexExample.java

public class HexUtilsToHexExample {
    public static void main(String... args) {
        String sample = "Simple Solution";
        byte[] data = sample.getBytes();

        // Convert Byte Array to Hex String
        String hexString = HexUtils.toHex(data);

        System.out.println("Hex String: " + hexString);
    }
}
The output as below.
Hex String: 53696d706c6520536f6c7574696f6e

Happy Coding 😊

Java Convert Hex String to Byte Array

How to Convert Object to Map in Java

Java Check a Valid TCP Port Number

Java How to Concatenate two Arrays