简体   繁体   中英

Convert char hex array to byte array java

How can I convert a char array of hex to byte array in Java? I don't want to convert char array to string for security reasons.

Is there any inbuilt library available for this conversion in Java 8?

There is no single Java SE method for it, but with Character.digit it's fairly straightforward:

byte[] parse(char[] hex) {
    int len = hex.length;
    if (len % 2 != 0) {
        throw new IllegalArgumentException(
            "Even number of digits required");
    }

    byte[] bytes = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        int high = Character.digit(hex[i], 16);
        int low = Character.digit(hex[i + 1], 16);
        bytes[i / 2] = (byte) (high << 4 | low);
    }

    return bytes;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM