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);
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?
Share Improve this question edited Mar 9 at 13:26 user2357112 283k31 gold badges482 silver badges564 bronze badges asked Mar 9 at 13:04 Mayank Kumar ChaudhariMayank Kumar Chaudhari 18.9k13 gold badges72 silver badges155 bronze badges 2 |1 Answer
Reset to default 4Uint8Array 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)
;
Uint8Array
gives you aUint8Array
array. Your title can use improvement because right now it's not at all informative to what you're trying to convey here. – VLAZ Commented Mar 9 at 13:31