Sudhanshu Gaur
Sudhanshu Gaur

Reputation: 7684

Nodejs code to convert hex string to byte array?

Can anyone please tell me equivalent Nodejs code to convert hex string to byte array which is in Java

public static byte[] hexStringToByteArray(String s) {
    byte[] b = new byte[s.length() / 2];
    for (int i = 0; i < b.length; i++) {
        int index = i * 2;
        int v = Integer.parseInt(s.substring(index, index + 2), 16);
        b[i] = (byte) v;

    }
    return b;
}

Upvotes: 3

Views: 14580

Answers (1)

Jake Holzinger
Jake Holzinger

Reputation: 6063

You can use Buffer.from(str, [encoding]) to perform the conversion.

Buffer.from(str, 'hex');

Upvotes: 19

Related Questions