Convert hex string to byte[] - Java java.lang

Java examples for java.lang:String Hex

Description

Convert hex string to byte[]

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String hexString = "java2s.com";
        System.out.println(java.util.Arrays
                .toString(hexStringToBytes(hexString)));
    }//from  w  w w  .  java2 s .  c o  m

    /**
     * Convert hex string to byte[]
     *
     * @param hexString the hex string
     * @return byte[]
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * Convert char to byte
     *
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}

Related Tutorials