Convert Uint8Array to hexadecimal 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 have any length, but let the length be 4.

I would like to have a function that converts uint8 to the equivalent of a hexadecimal string.

 var hex_string = convertUint8_to_hexStr(uint8); //hex_string becomes "1f2f3f4f" 
+5
source share
2 answers

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

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

Another solution: reduce :

 uint8.reduce(function(memo, i) { return memo + ('0' + i.toString(16)).slice(-2); //padd with leading 0 if <16 }, ''); 

Or map and join :

 uint8.map(function(i) { return ('0' + i.toString(16)).slice(-2); }).join(''); 
+1
source

All Articles