将二进制文件转换为 0 和 1 的字符串
Convert Binary file to strings of 0s and 1s
我有一个来自随机数生成器的二进制 .dat
文件,我需要将其转换为 0
和 1
的字符串。我在 python.
中找不到完美的解决方案
我现在的代码。需要将 quantis.dat
转换为 0
和 1
的字符串。
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 个数字。
我有一个来自随机数生成器的二进制 .dat
文件,我需要将其转换为 0
和 1
的字符串。我在 python.
我现在的代码。需要将 quantis.dat
转换为 0
和 1
的字符串。
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 个数字。