Convert hexadecimal string to an array of Uint8 values

Converting a string to an array of Uint8 values is often used in cryptography because it allows for the manipulation of individual bytes of data.

Converting a string to an array of Uint8 values is often used in cryptography because it allows for the manipulation of individual bytes of data. This can be useful in various encryption algorithms, such as AES, which operates on fixed block sizes of 128 bits (16 bytes). By converting a string to an array of Uint8 values, the data can be divided into 16-byte blocks and then encrypted using AES. Additionally, this conversion can be used to create a byte-level representation of a string, which can be useful for creating digital signatures or hash values of the data.

Here is the JavaScript code to do this:

const fromHex = (s) => {
    let result = new Uint8Array(s.length / 2);
    for (let i = 0; i < s.length / 2; i++) {
        result[i] = parseInt(s.substr(2 * i, 2), 16);
    }
    return result;
}

Or it can be done even simpler using Buffer:

new Uint8Array(Buffer.from(s, 'hex'));

Last updated