簡體   English   中英

這個正在解碼十六進制字符串然后將其編碼為 base64 的 Python 代碼將如何寫入 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=

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=

受十六進制到Uint8Array轉換的這個答案的啟發,以及Uint8Array到 base64 轉換的這個答案的啟發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM