Java Hex Convert To fromHexString(String s)

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

Description

Convert a string containing hexadecimal characters to a byte-array.

License

Open Source License

Parameter

Parameter Description
s a hex string

Return

a byte array with the corresponding value

Declaration

public static byte[] fromHexString(String s) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from   w  w w  . j av a 2  s . co m*/
     * Convert a string containing hexadecimal characters to a byte-array.
     *
     * @param s a hex string
     * @return a byte array with the corresponding value
     */
    public static byte[] fromHexString(String s) {
        char[] rawChars = s.toUpperCase().toCharArray();

        int hexChars = 0;
        for (int i = 0; i < rawChars.length; i++) {
            if ((rawChars[i] >= '0' && rawChars[i] <= '9')
                    || (rawChars[i] >= 'A' && rawChars[i] <= 'F')) {
                hexChars++;
            }
        }

        byte[] byteString = new byte[(hexChars + 1) >> 1];

        int pos = hexChars & 1;

        for (int i = 0; i < rawChars.length; i++) {
            if (rawChars[i] >= '0' && rawChars[i] <= '9') {
                byteString[pos >> 1] <<= 4;
                byteString[pos >> 1] |= rawChars[i] - '0';
            } else if (rawChars[i] >= 'A' && rawChars[i] <= 'F') {
                byteString[pos >> 1] <<= 4;
                byteString[pos >> 1] |= rawChars[i] - 'A' + 10;
            } else {
                continue;
            }
            pos++;
        }

        return byteString;
    }

    /**
     * Rewrite a byte array as a char array
     *
     * @param input -
     *              the byte array
     * @return char array
     */
    public static char[] toCharArray(byte[] input) {
        char[] result = new char[input.length];
        for (int i = 0; i < input.length; i++) {
            result[i] = (char) input[i];
        }
        return result;
    }
}

Related

  1. fromHexString(String s)
  2. fromHexString(String s)
  3. fromHexString(String s)
  4. fromHexString(String s)
  5. fromHexString(String s)
  6. fromHexString(String s, int offset, int length)
  7. fromHexString(String str)
  8. fromHexString(String text)
  9. fromHexString(String value)