Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does map over Uint8Array behave strangely?

I am trying to get mimeType from the image buffer or ArrayBuffer. But I am facing a strange issue.

I am using the following code to convert the signature bytes to hex string.

const uint8Array = new Uint8Array([137, 80, 78, 71]);
const signatureLength = 4;
const signature1 = uint8Array.slice(0, signatureLength).map(byte => {
  const signature = byte.toString(16).padStart(2, "0");
  console.log("signature --- ", signature, byte, typeof signature);
  return signature;
});
const signature = signature1.join("").toUpperCase();
console.log("signature 1 --- ", signature1, signature);

As you can see in the console output, 78 is actually converted to '4e', but in the map result it is saved as 0. This behaviour seems very strange. What is going on here?

like image 314
mayank1513 Avatar asked Oct 26 '25 05:10

mayank1513


1 Answers

Uint8Array is not a regular array. TypedArray.prototype.map() does not return an array of transformed values, instead it returns another TypedArray of the same type.

This is causing the map to convert '4e' to 0.

The solution if to use Array.from(slicedArray);

like image 186
mayank1513 Avatar answered Oct 27 '25 19:10

mayank1513