8

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.

2

4 Answers 4

14

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]
Sign up to request clarification or add additional context in comments.

3 Comments

Since node 11 this doesn't need to be imported anymore and is available on the global object
@baywet thanks! I removed it from the answer.
Worth noting that this also works in CloudFlare workers.
8

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

3 Comments

Amazing! It works like a charm when I replace TextEncoder with this in an environment that doesn't have support for TextEncoder.
This will only work correctly for ASCII characters. Characters outside the ASCII range (eg emoji) need more than 1 byte to encode in UTF8. This will generate garbage strings.
This works way better than TextEncoder because this doesn't impose a BOM
5

If you are coming from the future Buffer.from(string, encoding) is probably the best option.

const uint: Uint8Array = Buffer.from('string here', 'base64')

1 Comment

That's assuming Node. On the web, there's TextEncoder.
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) creates a JS number combining the input and given base - we're using base 16 in this case.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.