首页 > 解决方案 > 将二进制文件转换为 0 和 1 的字符串

问题描述

我有一个.dat来自随机数生成器的二进制文件,我需要将其转换为0s 和1s 的字符串。我在 python 中找不到一个优雅的解决方案。

我现在拥有的代码。需要转换quantis.dat0s 和1s 的字符串。

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()

标签: python-3.xfilebinaryfiles

解决方案


您可以将其用于字符串列表:

>>> [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 位。


推荐阅读