// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
public class Hex {
    public static void main(String[] args) {
        char c = 'a';
        System.out.println(Integer.toHexString(c));
        System.out.println(toHex(c));
        String hex = "61";
        System.out.println((char)Integer.parseInt(hex, 16));
        System.out.println(fromHex(hex));
        char[] c2 = { 'j', 'k', 'l', 'm', 'n', 'o' };
        System.out.println(toHex(c2));
        String hex2 = "6a6b6c6d6e6f";
        System.out.println(manyFromHex(hex2));
    }
    private static char hexdigit[] = { '0', '1', '2', '3', '4', '5', '6', '7',
                                       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    public static String toHex(char c) {
        StringBuffer sb = new StringBuffer("");
        sb.append(hexdigit[(c >> 4) & 0x0F]);
        sb.append(hexdigit[c & 0x0F]);
        return sb.toString();
    }
    public static String toHex(char[] c) {
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < c.length; i++) {
            sb.append(hexdigit[(c[i] >> 4) & 0x0F]);
            sb.append(hexdigit[c[i] & 0x0F]);
        }
        return sb.toString();
    }
    public static char fromHex(String hex) {
        return (char)(hexval(hex.charAt(0)) * 16 + hexval(hex.charAt(1)));
    }
    public static char[] manyFromHex(String hex) {
        int n = hex.length() / 2;
        char[] res = new char[n];
        for(int i = 0; i < n; i++) {
            res[i] = (char)(hexval(hex.charAt(2 * i)) * 16 + hexval(hex.charAt(2 * i + 1)));
        }
        return res;
    }
    private static int hexval(char c) {
        if(c >= '0' && c <= '9') {
            return c - '0';
        } else if(c >= 'A' && c <= 'F') {
            return c - 'A' + 10;
        } else if(c >= 'a' && c <= 'f') {
            return c - 'a' + 10;
        } else {
            return 0;
        }
    }
}
