我有一个来自随机数生成器的二进制.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位的二进制。