Java - Write code to convert byte array to Hex String via hex char table

Requirements

Write code to convert byte array to Hex String via hex char table

Hint

The hex char table is like

byte[] HEX_CHAR_TABLE = { (byte) '0', (byte) '1',
            (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6',
            (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b',
            (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f' };

Demo

//package com.book2s;

import java.io.UnsupportedEncodingException;

public class Main {
    public static void main(String[] argv) {
        byte[] raw = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toHexString(raw));
    }//from   w w w  .j  a  v  a 2s. co m

    private static final byte[] HEX_CHAR_TABLE = { (byte) '0', (byte) '1',
            (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6',
            (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b',
            (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f' };

    public static String toHexString(byte[] raw)
            throws IllegalArgumentException {
        final byte[] hex = new byte[2 * raw.length];
        int index = 0;

        for (final byte b : raw) {
            final int v = b & 0xFF;
            hex[index++] = HEX_CHAR_TABLE[v >>> 4];
            hex[index++] = HEX_CHAR_TABLE[v & 0xF];
        }
        try {
            return new String(hex, "ASCII");
        } catch (final UnsupportedEncodingException e) {
            throw new IllegalArgumentException("Illegal Hex string", e);
        }
    }
}