简体   繁体   中英

How to convert a hex binary string to Uint8Array

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

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

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

Buffer s 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 Uint8Array s wherever Buffer s are supported as well.

 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)

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