0

I've created a script which allows me to read the binary representation of a whole file, yet I couldn't find a way to write the binary stream back to a file using python.

The code I'm using to get the binary value is the following:

 fileBin = ""
 bytes = bytearray(open(file, "rb").read())
 for i in range(0, len(bytes)):
     fileBin = fileBin + str(('{:08b}'.format(bytes[i])))
 return fileBin
9
  • If I understood correctly you want to convert binary file to a file full of 0s and 1s. You could just open file normally and write it as a string. Commented May 1, 2017 at 15:36
  • @matejm maybe I wrote the post in a confused way: Given a binary string representing an entire file, I want to re-create the read file. Commented May 1, 2017 at 15:40
  • So you want just convert every 8 characters back to byte object? Commented May 1, 2017 at 15:52
  • No, I tried with byte and bytearray yet I have to find a way to create the file from the stream and not just write into a new file. Commented May 1, 2017 at 15:55
  • Looks like this is more of a copy operation, answered [here|stackoverflow.com/questions/16630789/… Commented May 1, 2017 at 18:13

1 Answer 1

0

I was able to find a solution and to write a whole new file using bytes. The problem is all about the code used to represent the string: while trying to write a bit string (i.e. "101010111000") I was actually writing its ASCII value in a text file.

what you need to do it:

  • take every 8 characters of the string
  • convert those characters in int
  • cast the result to end up with bytes (I casted a whole list)
  • profit

The code I used is the following:

    """Reads file as binary string"""
    def openFileBinary(file):
         fileBin = ""
         bytes = bytearray(open(file, "rb").read())
         for i in bytes:
             fileBin = fileBin + str(('{:08b}'.format(i)))
         return fileBin

    """Writes string to file as binary"""
    def writeFile(stream):
        with open("output", "wb") as f:
          f.write(bitstring_to_bytes(stream))

    """Converts binary string into bytes"""
    def bitstring_to_bytes(s):
        b = bytearray()
        w = [int(s[i:i+8],2) for i in range(0, len(s), 8)]
        return(bytes(w))
Sign up to request clarification or add additional context in comments.

1 Comment

It was a terrible solution to use strings! I've continued working on the project and rewrote the code to work with bytearrays only!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.