简体   繁体   中英

How would this Python code that is decoding a hex string and then encoding it to base64 be written in Javascript?

I'm currently porting over code from a Python program that is decoding and encoding a string in a somewhat long sequence of decode() and encode() calls. In Python it looks as follows:

import codecs
input = '3E061F00000E10FE'
data = codecs.encode(codecs.decode(input, "hex"), "base64").decode().strip()

When printed out in Python the result of data is: PgYfAAAOEP4=

I tried to reconstruct this in Javascript and Python by taking apart the whole encode/decode sequence and separating each function call so I could compare the two to see if I got the correct result from the Javascript version of the code. I was unsuccessful since the results from the Javascript and Python versions of the code were different.

So my question is if anybody knows what the equivalent of the Python code would be in Javascript.

Edit: Just to be clear, I'm in a Node.js environment

This solution first converts the hex string to a byte array, and then performs a base64-encoding of that byte array:

 const input = '3E061F00000E10FE'; const bytes = new Uint8Array(input.match(/.{1,2}/g).map(b => parseInt(b, 16))); const base64 = btoa(String.fromCharCode.apply(null, bytes)); console.log(base64);

This yields your expected output:

PgYfAAAOEP4=

Inspired by this answer for the hex to Uint8Array conversion, and this answer for the Uint8Array to base64 conversion.

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