我有一個來自亂數發生器的二進制.dat檔案,我需要將其轉換成0s和1s的字串。我在python中找不到一個優雅的解決方案。
我現在的代碼。需要將quantis.dat轉換為一個0s和1s的字串。
def bytesToBits(bytes)。
return bin(int(bytes. hex(), 16)
outfile = open("quantum.txt"/span>, "w")
infile = open("quantis.dat", "rb")
chunk = infile.read(1)
while chunk:
decimal = bytesToBits(chunk)
outfile.write(decimal)
chunk = infile.read(1)
outfile.close()
uj5u.com熱心網友回復:
你可以用它來處理一個字串的串列:
[f"{n。 08b}" for n in open("隨機。 dat", "rb").read()]
['01000001', '01100010', '01000010', '10011011', '01100111', ...
或者如果你想要一個單一的字串:
>>> ""。 join(f"{n: 08b}" for n in open("隨機。 dat", "rb").read())
'010000010110001001000010100110110110011100010110101101010111011...
:08b格式指定器將把每個位元組格式化為二進制,正好有8位數字。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/328087.html
標籤:
