Java Hex Convert To fromHex(String hex)

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

Description

from Hex

License

Apache License

Declaration

public static byte[] fromHex(String hex) 

Method Source Code

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

public class Main {

    public static byte[] fromHex(String hex) {
        return fromHex(hex, '0');
    }//  w  w w  .  j ava2s.c om

    public static byte[] fromHex(String hex, char padHex) {
        if (hex == null) {
            return null;
        }

        if ((hex.length() & 1) == 1) {
            hex += padHex;
        }

        char[] data = hex.toUpperCase().toCharArray();
        int len = data.length;

        byte[] out = new byte[len >> 1];
        for (int i = 0, j = 0; j < len; i++) {
            int f = hex2Int(data[j], j) << 4;
            j++;
            f = f | hex2Int(data[j], j);
            j++;
            out[i] = (byte) (f & 0xFF);
        }

        return out;
    }

    public static int length(byte[] array) {
        return (array == null ? 0 : array.length);
    }

    public static int length(byte[]... arrays) {
        int len = 0;
        if (arrays != null) {
            for (byte[] array : arrays) {
                if (array != null) {
                    len += array.length;
                }
            }
        }

        return len;
    }

    private static int hex2Int(char hex, int index) {
        int digit = Character.digit(hex, 16);
        if (digit == -1) {
            throw new RuntimeException(String.format("Illegal hex char %s at hex[%d]", hex, index));
        }

        return digit;
    }
}

Related

  1. fromHex(String hex)
  2. fromHex(String hex)
  3. fromHex(String hex)
  4. fromHex(String hex)
  5. fromHex(String hex)
  6. fromHex(String hexBytes)
  7. fromHex(String hexData)
  8. fromHex(String hexStr)
  9. fromHex(String hexString)