Python 2.7 - 将 base 64 转换为二进制字符串

标签 python python-2.7 base64

我正在使用 Python 2.7(这意味着没有 base64.decodebytes()) 我需要将我的 base64 字符串,例如 aW0ganVzdCBhIGJhc2UgNjQgZmlsZQ== 转换为二进制(即由 1 和 0 组成的字符串)。

我想尝试将 base 64 字符串写入 wb 模式的文件,然后用 rb 读回它,但即使使用 wb 写入 - 打开文件时我仍然看到原始的 base 64 字符串..

我错过了什么?

谢谢

最佳答案

您可以在列表理解中使用 ordformat 函数进行转换。

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/

相关文章:

python - 用于分析 Python 代码的峰值内存使用情况的模块

VB6 的 Base64 编码的 C# 版本

java - 如何从 Java 中的 pfx 获取 PEM Base 64?

sockets - SMTP 邮件服务器 (sendgrid) 提交时出错

python - 查找自上次使用 python imaplib2 检查后添加到 imap 邮箱的新邮件?

python - django.db.utils.IntegrityError : NOT NULL constraint failed 错误

function - 如何使用 OpenCV 和 Python 将鼠标位置保存在变量中?

python - 使用 Python 执行 GameFbxExporter Maya

python - pandas 中 drop 和 select_dtype 的区别

python - 标准输出 : CMake Error: No source or binary directory provided - Kivy Buildozer