1

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

wappa
  • 149
  • 1
  • 12

1 Answers1

2

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.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • 1
    Since I'm in a Node.js environment I had to create my own btoa function and remove 'new Uint8Array', by doing this I got the expected result. Thanks for the help! – wappa Sep 20 '19 at 08:55