create a byte-array from a hexidecimal string accepts tokenized (0x leading) and non-tokenized hex strings - Java java.lang

Java examples for java.lang:String Hex

Requirements

create a byte-array from a hexidecimal string accepts tokenized (0x leading) and non-tokenized hex strings

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(bytesFromHexString(hexString)));
    }/* w w  w  . j  a va  2 s  . c  o  m*/

    private static final int RADIX = 16;
    private static final String HEX_TOKEN = "0x";

    /**
     * create a byte-array from a hexidecimal string
     * accepts tokenized (0x leading) and non-tokenized hex strings
     * 
     * @param hexString
     * @return byte[]
     * @throws IllegalArgumentException
     */

    public static byte[] bytesFromHexString(String hexString) {

        if (hexString.startsWith(HEX_TOKEN)) {
            hexString = hexString.substring(HEX_TOKEN.length());
        }

        int length = (int) hexString.length() / 2;

        if (0 == length) {
            throw new IllegalArgumentException("zero length string");
        }

        if ((hexString.length() % 2) != 0) {
            throw new IllegalArgumentException("odd length string");
        }

        byte tempArray[] = new byte[length];

        for (int i = 0; i < length; i++) {

            // fail if we can't convert into bytes
            try {
                String temp = hexString.substring((i * 2), (i * 2) + 2);
                char digs[] = temp.toCharArray();
                int theValue = Character.digit(digs[0], RADIX) * RADIX;

                theValue += Character.digit(digs[1], RADIX);
                tempArray[i] = (byte) theValue;
            } catch (Exception e) {
                throw new IllegalArgumentException(
                        "improperly formed hex string");
            }
        }

        return tempArray;
    }
}

Related Tutorials