How to convert hexadecimal strings to byte arrays in Java

Asked 1 years ago, Updated 1 years ago, 142 views

I'm looking for a way to convert a long hexadecimal string into a byte array.

If I have the string "00A0BF", I want to change it to {0x00, 0xA0, 0xBF} byte[], what should I do? I'm a beginner at Java, but other sources look a little dirty and I'd like to find a cleaner sauce.

java byte hex dump

2022-09-22 14:15

1 Answers

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

Do it like this.


2022-09-22 14:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.