Convert a String containing consecutive (no inside whitespace) hexadecimal digits into a corresponding byte array. - Java java.lang

Java examples for java.lang:String Hex

Description

Convert a String containing consecutive (no inside whitespace) hexadecimal digits into a corresponding byte array.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String text = "java2s.com";
        System.out.println(java.util.Arrays.toString(fromHexString(text)));
    }//from   ww w .j av a 2 s .com

    /**
     * Convert a String containing consecutive (no inside whitespace) hexadecimal
     * digits into a corresponding byte array. If the number of digits is not even,
     * a '0' will be appended in the front of the String prior to conversion.
     * Leading and trailing whitespace is ignored.
     * @param text input text
     * @return converted byte array, or null if unable to convert
     */
    public static byte[] fromHexString(String text) {
        text = text.trim();
        if (text.length() % 2 != 0)
            text = "0" + text;
        int resLen = text.length() / 2;
        int loNibble, hiNibble;
        byte[] res = new byte[resLen];
        for (int i = 0; i < resLen; i++) {
            int j = i << 1;
            hiNibble = charToNibble(text.charAt(j));
            loNibble = charToNibble(text.charAt(j + 1));
            if (loNibble == -1 || hiNibble == -1)
                return null;
            res[i] = (byte) (hiNibble << 4 | loNibble);
        }
        return res;
    }

    private static final int charToNibble(char c) {
        if (c >= '0' && c <= '9') {
            return c - '0';
        } else if (c >= 'a' && c <= 'f') {
            return 0xa + (c - 'a');
        } else if (c >= 'A' && c <= 'F') {
            return 0xA + (c - 'A');
        } else {
            return -1;
        }
    }
}

Related Tutorials