Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to Uint8Array in javascript

Tags:

javascript

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.

like image 993
Robbal Avatar asked Jun 05 '26 09:06

Robbal


2 Answers

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]
like image 170
ximo Avatar answered Jun 06 '26 21:06

ximo


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()))
like image 34
Diego Corcuera Camero Avatar answered Jun 06 '26 23:06

Diego Corcuera Camero