Java - Write code to convert hex to byte and throw exception if needed

Requirements

Write code to convert hex to byte and throw exception if needed

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String hexStr = "book2s.com";
        int len = 42;
        System.out/* w  w w. java  2  s. co  m*/
                .println(java.util.Arrays.toString(hex2byte(hexStr, len)));
    }

    /**
     * 
     * @param hexStr
     * @param len
     * @return
     * @throws AssertionError
     */
    public static byte[] hex2byte(String hexStr, int len)
            throws AssertionError {
        if ((len % 2) != 0)
            throw new AssertionError(
                    "Hex2Byte() fail: len should be divided by 2");

        byte[] buf = new byte[len / 2];
        for (int i = 0, j = 0; i < len; i += 2, j++) {
            byte hi = (byte) Character.toUpperCase(hexStr.charAt(i));
            byte lo = (byte) Character.toUpperCase(hexStr.charAt(i + 1));
            if (!Character.isDigit((char) hi) && !(hi >= 'A' && hi <= 'F'))
                throw new AssertionError(
                        "Hex2Byte() fail: hex string is invalid in " + i
                                + " with char '" + hexStr.charAt(i) + "'");
            if (!Character.isDigit((char) lo) && !(lo >= 'A' && lo <= 'F'))
                throw new AssertionError(
                        "Hex2Byte() fail: hex string is invalid in "
                                + (i + 1) + " with char '"
                                + hexStr.charAt(i + 1) + "'");

            int ch = 0;
            ch |= (Character.isDigit((char) hi) ? (hi - '0')
                    : (0x0a + hi - 'A')) << 4;
            ch |= (Character.isDigit((char) lo) ? (lo - '0')
                    : (0x0a + lo - 'A'));
            buf[j] = (byte) ch;
        }

        return buf;
    }
}