Search code examples
node.jsstring-conversion

Convert Uint8Array into hex string equivalent in Node.js


I am using Node.js v4.5. Suppose I have this Uint8Array variable.

var uint8 = new Uint8Array(4);
uint8[0] = 0x1f;
uint8[1] = 0x2f;
uint8[2] = 0x3f;
uint8[3] = 0x4f;

This array can be of any length but let's assume the length is 4.

I would like to have a function that that converts uint8 into the hex string equivalent.

var hex_string = convertUint8_to_hexStr(uint8);
// hex_string becomes "1f2f3f4f"

Solution

  • You can use Buffer.from() and subsequently use toString('hex'):

    let hex = Buffer.from(uint8).toString('hex');