How to convert byte array to hex string in Java 1.8

If you like cryptography you might know that sometimes you have a byte array which you wish to convert to hexadecimal string. In java, to this day, I haven’t found yet a native class that does it, I’ve spent several minutes on the Internet looking for something like the Base64 class.

Turns out Apache commons has a class called Hex.java which has all these methods. Thank you Apache!

Anyway, I have extracted just the necessary code to create a class called HexTools.java which contains a method called byteArraytoHexString which does precisely what I need. Here is the class.

/*
 * This class was created with the same code contained in Hex.java
 * The original class is here:
 * https://commons.apache.org/proper/commons-codec/apidocs/src-html/org/apache/commons/codec/binary/Hex.html
 */
public class HexTools {
    
    // Used to build output as Hex
    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    
    // Used to build output as Hex
    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
     * The returned array will be double the length of the passed array, as it takes two characters to represent any
     * given byte.
     *
     * @param data
     *            a byte[] to convert to Hex characters
     * @param toLowerCase
     *            <code>true</code> converts to lowercase, <code>false</code> to uppercase
     * @return A char[] containing hexadecimal characters
     * @since 1.4
     */
    public static String byteArraytoHexString(final byte[] data, final boolean toLowerCase) {
        return new String(encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER));
    }
    
    /**
     * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
     * The returned array will be double the length of the passed array, as it takes two characters to represent any
     * given byte.
     *
     * @param data
     *            a byte[] to convert to Hex characters
     * @param toDigits
     *            the output alphabet
     * @return A char[] containing hexadecimal characters
     * @since 1.4
     */
    private static char[] encodeHex(final byte[] data, final char[] toDigits) {
        final int l = data.length;
        final char[] out = new char[l << 1];
        
        // Two chars form the hex value
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = toDigits[ (0xF0 & data[i]) >>> 4 ];
            out[j++] = toDigits[ 0x0F & data[i]];
        }
        return out;
    }
    
}

It is all static so that it can be used without having to create any instances of it. Like so.

import java.util.Random;

public class RandomByteArrayToHexExample {
    
    public static void main (String args[]) {
        try {
            
            byte[] b = new byte[64];
            new Random().nextBytes(b);
            
            String out = HexTools.byteArraytoHexString(b, false);
            
            System.out.println(out);
            
        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }
}

The result of executing the code above is the following:

c:experimentsKeyPairGenerators>java RandomByteArrayToHexExample
5793DF5AE3268C786F9F6A3811678B274F9D19EBA86E68FDB1FCBEC8D85BF0AD75ED49E5EDDFC05641A1B95E91A600CAE104DF76B720062814F25BDB291D0AFF

An array of 64 bytes in length is filled with random values and then converted to a hexadecimal string of 128 chars in length. Just to demonstrate that the method works.

Sources

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: