简体   繁体   English

大于 0x99 的 Uint8Array 值打印为 0

[英]Uint8Array values above 0x99 are printed as 0

I'm trying to read a binary file and pull out parts of it to print in hexadecimal.我正在尝试读取一个二进制文件并提取其中的一部分以十六进制打印。 I have to read a file from the host (using FileReader 's readAsArrayBuffer ).我必须从主机读取文件(使用FileReaderreadAsArrayBuffer )。 I noticed that something kept printing 0, and I can't figure out why.我注意到有些东西一直在打印 0,我不知道为什么。

Here's a minimal way to reproduce it:这是重现它的最小方法:

let t = new Uint8Array([ 0x26, 0xa6, 0x01, 0x99 ]);
console.log("T: " + t.map(b => b.toString(16)).join(" "));

Output:输出:

T: 26 0 1 99

It seems like any value over 0x99 just gets printed as 0. If I initialize it with an array, like似乎任何超过0x99值都会打印为 0。如果我用数组初始化它,比如
let t = [ 0x26, 0xa6, 0x01, 0x99 ];
then it works.那么它的工作原理。

It also works if I call Array.from() on the Uint8Array before calling "map" on it.如果我在 Uint8Array 上调用“map”之前调用 Array.from() ,它也可以工作。 Any help is appreciated.任何帮助表示赞赏。

map on a typed array creates the same kind of typed array.类型化数组上的map创建相同类型的类型化数组。 Since you're returning strings from your callback, they get converted to integers that will fit in the type of the element of the array, or 0 if they can't be converted.由于您从回调中返回字符串,因此它们会被转换为适合数组元素类型的整数,如果无法转换则为 0。 The string "a6" (for instance) can't be converted implicitly, so you get 0 instead.字符串"a6" (例如)无法隐式转换,因此您会得到0

Use the mapping facility of Array.from instead to create an array of strings from the callback that you can join together:使用Array.from的映射工具从可以join在一起的回调创建一个字符串数组:

 let t = new Uint8Array([ 0x26, 0xa6, 0x01, 0x99 ]); console.log("T: " + Array.from(t, b => b.toString(16)).join(" "));


It's worth noting that the 26 you're getting in the output from your original code is misleading.值得注意的是,您在原始代码的输出中得到的26具有误导性。 :-) That's the decimal value 26 (whereas 0x26 is 38 in decimal). :-) 那是十进制值 26(而0x26是十进制的38 )。 You're passing in 0x26 , which gets converted to "26" , which gets converted to 26 (decimal, not hex), then converted back to "26" by the join function.您传入0x26 ,它被转换为"26" ,它被转换为26 (十进制,而不是十六进制),然后通过join函数转换回"26"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM