Java Hex Convert To fromHexString(String text)

Here you can find the source of fromHexString(String text)

Description

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

License

Apache License

Parameter

Parameter Description
text input text

Return

converted byte array, or null if unable to convert

Declaration

public static byte[] fromHexString(String text) 

Method Source Code

//package com.java2s;
/*// w ww.j a  v a 2s .c om
 * Copyright 2009-2013 Scale Unlimited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

public class Main {
    /**
     * 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

  1. fromHexString(String s)
  2. fromHexString(String s)
  3. fromHexString(String s)
  4. fromHexString(String s, int offset, int length)
  5. fromHexString(String str)
  6. fromHexString(String value)
  7. fromHexToBytes(String hex)