简体   繁体   中英

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 ). I noticed that something kept printing 0, and I can't figure out why.

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
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. Any help is appreciated.

map on a typed array creates the same kind of typed array. 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. The string "a6" (for instance) can't be converted implicitly, so you get 0 instead.

Use the mapping facility of Array.from instead to create an array of strings from the callback that you can join together:

 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. :-) That's the decimal value 26 (whereas 0x26 is 38 in decimal). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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