我正在使用 Python 2.7(这意味着没有 base64.decodebytes()
)
我需要将我的 base64 字符串,例如 aW0ganVzdCBhIGJhc2UgNjQgZmlsZQ==
转换为二进制(即由 1 和 0 组成的字符串)。
我想尝试将 base 64 字符串写入 wb
模式的文件,然后用 rb
读回它,但即使使用 wb
写入 - 打开文件时我仍然看到原始的 base 64 字符串..
我错过了什么?
谢谢
最佳答案
您可以在列表理解中使用 ord
和 format
函数进行转换。
import base64
data = 'aW0ganVzdCBhIGJhc2UgNjQgZmlsZQ=='
print [format(ord(c), '08b') for c in base64.b64decode(data)]
输出
['01101001', '01101101', '00100000', '01101010', '01110101', '01110011', '01110100', '00100000', '01100001', '00100000', '01100010', '01100001', '01110011', '01100101', '00100000', '00110110', '00110100', '00100000', '01100110', '01101001', '01101100', '01100101']
如果你想把它作为一个字符串,只需.join
它:
''.join([format(ord(c), '08b') for c in base64.b64decode(data)])
关于Python 2.7 - 将 base 64 转换为二进制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48152403/