[英]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=
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. 我没有成功,因为代码的 Javascript 和 Python 版本的结果不同。
所以我的问题是,是否有人知道 Javascript 中的 Python 代码的等价物是什么。
编辑:为了清楚起见,我在 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);
这会产生您预期的 output:
PgYfAAAOEP4=
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.