Home > Blockchain >  How to convert a hex binary string to Uint8Array
How to convert a hex binary string to Uint8Array

Time:07-21

I have this string of bytes represented in hex:

const s = "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\x8bV23J15O4\xb14\xb1H61417KKLL\xb50L5U\x8a\x05\x00\xf6\xaa\x8e.\x1c\x00\x00\x00"

I would like to convert it to Uint8Array in order to further manipulate it.

How can it be done?

Update:

The binary string is coming from python backend. In python I can create this representation correctly:

encoded = base64.b64encode(b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\x8bV23J15O4\xb14\xb1H61417KKLL\xb50L5U\x8a\x05\x00\xf6\xaa\x8e.\x1c\x00\x00\x00')

CodePudding user response:

Since JavaScript strings support \x escapes, this should work to convert a Python byte string to a Uint8Array :

const s = "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\x8bV23J15O4\xb14\xb1H61417KKLL\xb50L5U\x8a\x05\x00\xf6\xaa\x8e.\x1c\x00\x00\x00";

const array = Uint8Array.from([...s].map(v => v.charCodeAt(0)));

console.log(array);

CodePudding user response:

In Node.js, one uses Buffer.from to convert a (base64-encoded) string into a Buffer.

If the original argument is a base64 encoded string, as in Python:

const buffer = Buffer.from(encodedString, 'base64');

It if's a UTF-8 encoded string:

const buffer = Buffer.from(encodedString);

Buffers are instances of Uint8Array, so they can be used wherever a Uint8Array is expected. Quoting from the docs:

The Buffer class is a subclass of JavaScript's Uint8Array class and extends it with methods that cover additional use cases. Node.js APIs accept plain Uint8Arrays wherever Buffers are supported as well.

CodePudding user response:

const s = "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\x8bV23J15O4\xb14\xb1H61417KKLL\xb50L5U\x8a\x05\x00\xf6\xaa\x8e.\x1c\x00\x00\x00"

//btoa(base64) - transforms base64 to ascii
let str = btoa(s)

let encoder = new TextEncoder()

let typedarr = encoder.encode(str) //encode() returns Uint8Array

console.log(typedarr)

  • Related