最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does map over Uint8Array behave strangely? - Stack Overflow

programmeradmin3浏览0评论

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
  • It's not at all strange that mapping over Uint8Array gives you a Uint8Array 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
  • Thanks for the comment. Can you please suggest a better title. – Mayank Kumar Chaudhari Commented Mar 9 at 16:40
Add a comment  | 

1 Answer 1

Reset to default 4

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);

发布评论

评论列表(0)

  1. 暂无评论