I have a string "ab05d705" and I am trying to convert it to the following so I can add it to a Uint8Array. So how do I convert the string "ab05d705" to
0xab,0x05,0xd7,0x05
to put into the following
var data = new Uint8Array([0xab,0x05,0xd7,0x05]);
Any help would be so appreciated.
You can use the Web API TextEncoder to get a Uint8Array of UTF-8 bytes from a string:
const encoded = new TextEncoder().encode('€')
console.log(encoded) // Uint8Array(3) [226, 130, 172]
A Uint8Array is basically an array full of charcodes, so you could split all the characters and convert them to charcodes, and then using that array and calling Uint8Array.from on it. Something like this should work:
var string = "Hello World!"
var uint8 = Uint8Array.from(string.split("").map(x => x.charCodeAt()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With