Java Hex Convert To fromHexString(String hex)

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

Description

Converts the given hex string to a byte array.

License

Apache License

Declaration

public static byte[] fromHexString(String hex) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /** Converts the given hex string to a byte array. */
    public static byte[] fromHexString(String hex) {
        int len = hex.length();
        if (len % 2 != 0)
            throw new IllegalArgumentException("Not a hex string");
        byte[] bytes = new byte[len / 2];
        for (int i = 0, j = 0; i < len; i += 2, j++) {
            int high = hexDigitToInt(hex.charAt(i));
            int low = hexDigitToInt(hex.charAt(i + 1));
            bytes[j] = (byte) ((high << 4) + low);
        }/*from  w w  w. java  2  s  . co m*/
        return bytes;
    }

    private static int hexDigitToInt(char c) {
        if (c >= '0' && c <= '9')
            return c - '0';
        if (c >= 'A' && c <= 'F')
            return c - 'A' + 10;
        if (c >= 'a' && c <= 'f')
            return c - 'a' + 10;
        throw new IllegalArgumentException("Not a hex digit: " + c);
    }
}

Related

  1. fromHexString(final String s)
  2. fromHexString(final String str)
  3. fromHexString(String encoded)
  4. fromHexString(String encoded)
  5. fromHexString(String hex)
  6. fromHexString(String hexString)
  7. fromHexString(String hexString)
  8. fromHexString(String hexString)
  9. fromHexString(String hexString)