简体   繁体   中英

Convert string to Uint8Array in 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.

try this:

var s = "ab05d705";
var result = [];

for(var i = 0; i < s.length; i+=2)
{
    result.push(parseInt(s.substring(i, i + 2), 16));
}
result = Uint8Array.from(result)
console.log(result);

parseInt(value, base);
This function converts a value with the given base, to a value with the base 10

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())

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