Java - Write code to convert String to Byte Array with shift operator

Requirements

Write code to convert String to Byte Array with shift operator

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String hexString = "book2s.com";
        System.out.println(java.util.Arrays
                .toString(toByteArray(hexString)));
    }//from   w ww  . ja  v a 2s .co  m

    public static final byte[] toByteArray(String hexString) {
        if (hexString == null || hexString.length() % 2 != 0)
            return null;
        hexString = hexString.toLowerCase();
        char[] cs = hexString.toCharArray();
        byte[] bs = new byte[cs.length / 2];
        for (int i = 0; i < bs.length; i++) {
            char b1 = cs[i * 2];
            char b2 = cs[i * 2 + 1];
            bs[i] = (byte) ((b1 > 'a' ? b1 - 'a' : b1 - '0') << 4 + (b2 > 'a' ? b2 - 'a'
                    : b2 - '0'));
        }
        return bs;
    }
}

Related Exercise