My Insight

Converting from byte[] (array) to hex string in Java

Hello there!

I just wanted to share a small piece of code I wrote way back in 2011 when I was working at my previous company. Yep, that was ages ago 🤭.

It’s a simple utility function I created to convert a byte[] into a hexadecimal String. Nothing fancy, but still useful even today!

public class Utils
{
    private static String digits = "0123456789abcdef";

    /**
     * Return length many bytes of the passed in byte array as a hex string.
     * @param data the bytes to be converted.
     * @param length the number of bytes in the data block to be converted.
     * @return a hex representation of length bytes of data.
     */
    public static String toHex(byte[] data, int length)
    {
        StringBuffer    buf = new StringBuffer();

        for (int i = 0; i != length; i++)
        {
            int v = data[i] & 0xff;
            buf.append(digits.charAt(v >> 4));
            buf.append(digits.charAt(v & 0xf));
        }

        return buf.toString();
    }

    /**
     * Return the passed in byte array as a hex string.
     * @param data the bytes to be converted.
     * @return a hex representation of data.
     */
    public static String toHex(byte[] data)
    {
        return toHex(data, data.length).toUpperCase();
    }
}

Its pretty simple code isn’t it? 😉

That’s all folks! Happy coding! 🥰😍


Leave a Reply

Your email address will not be published. Required fields are marked *