Java - Write code to convert hex String To Byte Array

Requirements

Write code to convert hex String To Byte Array

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String s = "book2s.com";
        System.out.println(java.util.Arrays
                .toString(hexStringToByteArray(s)));
    }//from   w ww. jav a2 s  .c o m

    public static byte[] hexStringToByteArray(String s) {
        if (s == null) {
            return null;
        }

        final int len = s.length();
        final byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            final int hiNibble = Character.digit(s.charAt(i), 16);
            final int loNibble = Character.digit(s.charAt(i + 1), 16);

            if (hiNibble < 0 || loNibble < 0) {
                throw new IllegalArgumentException(
                        "no valid hex number at offset " + i);
            }

            data[i / 2] = (byte) ((hiNibble << 4) + loNibble);
        }
        return data;
    }
}