python-3.x - 将二进制文件转换为 0 和 1 的字符串
问题描述
我有一个.dat
来自随机数生成器的二进制文件,我需要将其转换为0
s 和1
s 的字符串。我在 python 中找不到一个优雅的解决方案。
我现在拥有的代码。需要转换quantis.dat
为0
s 和1
s 的字符串。
def bytesToBits(bytes):
return bin(int(bytes.hex(), 16))
outfile = open("quantum.txt", "w")
infile = open("quantis.dat", "rb")
chunk = infile.read(1)
while chunk:
decimal = bytesToBits(chunk)
outfile.write(decimal)
chunk = infile.read(1)
outfile.close()
解决方案
您可以将其用于字符串列表:
>>> [f"{n:08b}" for n in open("random.dat", "rb").read()]
['01000001', '01100010', '01000010', '10011011', '01100111', ...
或者如果你想要一个字符串:
>>> "".join(f"{n:08b}" for n in open("random.dat", "rb").read())
'010000010110001001000010100110110110011100010110101101010111011...
:08b
格式说明符将每个字节格式化为二进制,正好有 8 位。
推荐阅读
- java - JAVA - 更改成员枚举函数中的非静态类字段
- java - 如何将 Struts2 迭代器值分配给会话
- javascript - 如何在 react-select 组件上添加图标和工具提示?
- javascript - 未为 eventSource 触发 onmessage 函数
- c# - 无法使用存储过程从 SQL Server 检索数据
- sql - 标准 SQL - 删除表 1 中存在于表 2 中的所有行
- python-3.x - 如何在 django-rest-framework 中检查数据库中是否存在数据
- python - 如何访问嵌套按钮的 on_press 处理程序?
- mongodb - 如何使用查找在 mongo 中加入两个集合
- python - 将python文件转换为带有图像的exe