2

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.

Jeroen
  • 56,917
  • 35
  • 193
  • 305
Robbal
  • 51
  • 1
  • 1
  • 8
  • http://stackoverflow.com/a/57805/251311 – zerkms Jan 22 '16 at 12:25
  • Possible duplicate of [How can I instantiate an ArrayBuffer from a hexadecimal representation of an octet stream?](http://stackoverflow.com/questions/29545531/how-can-i-instantiate-an-arraybuffer-from-a-hexadecimal-representation-of-an-oct) – Thilo Jan 22 '16 at 12:33

2 Answers2

3

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

Sammy
  • 648
  • 5
  • 22
1

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