Unable to get Uint8Array bytes

Viewed 274

I created an array buffer by var uni = new Uint8Array([255, 216, 255, 0, 0, 0, 0, 0]) But when I try to get back the bytes using map uni.map(byte => byte.toString(16)) it returns Uint8Array(8) [0, 0, 0, 0, 0, 0, 0, 0]

2 Answers

You have to convert TypedArray to Array first: Array.prototype.slice.call(uni).map(byte=>byte.toString(16))

The Uint8Array can only contain 8-bit unsigned integers (integers between 0 and 255). When you use the Uint8Array.protoype.map() method, trying to transform each element into a string, they get out of the [0, 255] range and are set to 0.

If you want to transform them into strings, you first transform the Uint8Array into a normal Array and them use the Array.prototype.map():

const array = Array.from(uni)
array.map(byte => byte.toString(16))
Related