6

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
  • 60,696
  • 40
  • 206
  • 339
Robbal
  • 101
  • 1
  • 2
  • 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

4 Answers4

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()))
Ben Wheeler
  • 6,788
  • 2
  • 45
  • 55
  • 1
    Amazing! It works like a charm when I replace `TextEncoder` with this in an environment that doesn't have support for `TextEncoder`. – Saiansh Singh Sep 17 '22 at 23:58
  • 2
    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. – Joseph Feb 01 '23 at 06:51
  • This works way better than TextEncoder because this doesn't impose a BOM – Sean Apr 08 '23 at 20:04
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')
Kmelow
  • 203
  • 1
  • 3
  • 12
  • That's assuming Node. On the web, there's [TextEncoder](https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder). – ximo Feb 24 '23 at 16:42
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.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
TheBrain
  • 685
  • 6
  • 26
3

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]

In node, TextEncoder is available from node:util:

import { TextEncoder } from 'node:util'
// const { TextEncoder } = require('node:util')
Andrew
  • 718
  • 1
  • 7
  • 25
ximo
  • 192
  • 1
  • 8