Convert Uint8Array into hex string equivalent in node.js

user6064424 picture user6064424 · Aug 30, 2016 · Viewed 15.8k times · Source

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"

Answer

robertklep picture robertklep · Aug 30, 2016

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

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