这个 Python 解码十六进制字符串然后将其编码为 base64 的代码如何写在 Javascript 中?

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

我目前正在从一个 Python 程序移植代码,该程序在一段较长的 decode() 和 encode() 调用序列中对字符串进行解码和编码。在 Python 中,它看起来如下:

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

在Python中打印出来的数据结果是:PgYfAAAOEP4=

我试图在 Javascript 和 Python 中重建它,方法是拆开整个 encode/decode 序列并分离每个函数调用,这样我就可以比较两者,看看我是否得到了Javascript 版本代码的正确结果。我没有成功,因为代码的 Javascript 和 Python 版本的结果不同。

所以我的问题是,是否有人知道 Python 代码在 Javascript.

中的等价物是什么?

编辑:澄清一下,我处于 ​​Node.js 环境

此解决方案首先将十六进制字符串转换为字节数组,然后对该字节数组执行 base64 编码:

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

这会产生您预期的输出:

PgYfAAAOEP4=

for the hex to Uint8Array conversion, and this answer 的启发,用于 Uint8Array 到 base64 的转换。