Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uint8Array.map(...) unexpected behaviour

Tags:

javascript

I tried to call .map on Uint8Array and got a surprise.

const tt = new Uint8Array(1);
tt[0] = 0xFF;

const ttt = tt.map(x => x.toString(2));

console.log(ttt[0]);
console.log(tt[0].toString(2));

I expected both output to be '11111111', but first console.log prints the number 199. Why?

like image 741
igorman007 Avatar asked Dec 21 '25 04:12

igorman007


1 Answers

That's because Uint8Array.map returns a Uint8Array. All the strings you return, get parsed as uint8s again ... and thus you get 199 (11111111 & (2 ** 8 - 1)).

You might wanna do:

 Array.from(tt).map(x => x.toString(2))
like image 53
Jonas Wilms Avatar answered Dec 23 '25 18:12

Jonas Wilms