Convert Uint8Array into hex string equivalent in node.js
You can use Buffer.from()
and subsequently use toString('hex')
:
let hex = Buffer.from(uint8).toString('hex');
Another solution:
Base function to convert int8 to hex:
// padd with leading 0 if <16
function i2hex(i) {
return ('0' + i.toString(16)).slice(-2);
}
reduce
:
uint8.reduce(function(memo, i) {return memo + i2hex(i)}, '');
Or map
and join
:
Array.from(uint8).map(i2hex).join('');
Buffer.from
has multiple overrides.
If it is called with your uint8
directly, it unnecessarily copies its content because it selects Buffer.from( <Buffer|Uint8Array> )
version.
You should call Buffer.from( arrayBuffer[, byteOffset[, length]] )
version which does not copy and just creates a view of the buffer.
let hex = Buffer.from(uint8.buffer,uint8.byteOffset,uint8.byteLength).toString('hex');