Home > database >  Convert Binary file to strings of 0s and 1s
Convert Binary file to strings of 0s and 1s

Time:09-22

I have a binary .dat file from a random number generator which I need to convert to strings of 0s and 1s. I can't find an elegant solution for this in python.

The code that I have now. Need to convert quantis.dat as a string of 0s and 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()

CodePudding user response:

You can use this for a list of strings:

>>> [f"{n:08b}" for n in open("random.dat", "rb").read()]
['01000001', '01100010', '01000010', '10011011', '01100111', ...

or if you want a single string:

>>> "".join(f"{n:08b}" for n in open("random.dat", "rb").read())
'010000010110001001000010100110110110011100010110101101010111011...

The :08b format specifier will format each byte as binary, having exactly 8 digits.

  • Related