35

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"
Yves M.
31.3k24 gold badges110 silver badges153 bronze badges
asked Aug 30, 2016 at 10:34
1

4 Answers 4

81

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

let hex = Buffer.from(uint8).toString('hex');
answered Aug 30, 2016 at 10:45

2 Comments

This is a good answer for the Node.js use case, but it is not compatible with Deno or the browser.
@FilipSeman good thing the question was tagged with node.js then :D
15

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('');
answered Aug 30, 2016 at 10:48

3 Comments

This does not padd correctly when the decimal value is <16. Here's a fixed version uint8.reduce(function(memo, i) { return memo + ("0"+i.toString(16)).slice(-2); }, '');
Second method works only for an Array but not Uint8Array, as the map function tries to write a string to the array (for Uint8Array it is casted to a number and evaluates to zero when there is a letter in the hex number). Workaround is to use Array.from(uint8) instead of uint8.
Slight modernization: uint8.reduce((t, x) => t + x.toString(16).padStart(2, '0'), '')
7

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');
answered Feb 16, 2022 at 12:55

1 Comment

Relevant documentation here: nodejs.org/api/…
7

Buffer is Node.js specific.

This is a version that works everywhere:

const uint8 = new Uint8Array(4);
uint8[0] = 0x1f;
uint8[1] = 0x2f;
uint8[2] = 0x3f;
uint8[3] = 0x4f;
function convertUint8_to_hexStr(uint8) {
 return Array.from(uint8)
 .map((i) => i.toString(16).padStart(2, '0'))
 .join('');
}
convertUint8_to_hexStr(uint8);
MonstraG
3903 silver badges10 bronze badges
answered Jan 27, 2023 at 15:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.