Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get an array of strings based on Uint8Array values (map Uint8 values to String/s)

new Uint8Array([1,2,3]).map((v,y)=>"0"+v+"0"+y)
> Uint8Array(3) [ 100, 201, 46 ] // actual
> ["0100","0201","0302"] // expected

new Uint8Array([1,2,3]).map((v,y)=>v+1)
> Uint8Array(3) [ 2, 3, 4 ] // actual as expected

[1, 2, 3].map(x => "0"+x);
> Array ["01", "02", "03"]  // actual as expected

Since 302 is bigger than 256 (Uint8 max size), when converted we get 302%256 which is 46.
Put this in as a proof we don’t get just any number type, but specifically Uint8.

So how do I get an array of strings based on Uint8Array values?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

the problem here is that Uint8Array.map returns an Uint8Array object
you need to convert it in a normal array in order to achieve the result you are looking for

const uint8Array = new Uint8Array([1,2,3])

const res1 = uint8Array.map((v,y)=>"0"+v+"0"+y)
const res2 = [...uint8Array].map((v,y)=>"0"+v+"0"+y)
console.log(res1, res2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading