0

I am using Python 3.10 and I am trying to read a Windows executable file, and output the binary data in a text format (1's and 0's) into a text file. I only require the binary, I do not want the offsets and the ASCII representation of the bytes. I do not want any spaces or new lines.

total = ""
with open("input.exe", "rb") as f:
    while (byte := f.read(1)):
        total = total + byte.decode("utf-8")
with open("output.txt", "w") as o:
    o.write(total)

However, it is not working, I am presented with the following error.

Traceback (most recent call last):
    File "converter.py", line 4, in <module>
        total = total + byte.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x90 in position 0: invalid start byte
5
  • 1
    That's because it's not possible to convert all binary bytes to ASCII. Commented Oct 26, 2021 at 14:13
  • Given, for example, the binary A\0 (letter A + NUL character), what would you expect in your text file? Commented Oct 26, 2021 at 14:14
  • I do not want to convert it into ASCII. I want my HelloWorld.exe program converts into a text file which shows its binary representation. Commented Oct 26, 2021 at 14:35
  • (ASCII was a typo -- sorry. Meant utf8.) Are you thinking like a hexdump, like od? Commented Oct 26, 2021 at 14:36
  • I want my output.txt file to contain 1010010101101000011101010101010101000111110101 as an example. Commented Oct 26, 2021 at 14:37

1 Answer 1

1

This code should do what you want:

with open("input.exe", "rb") as f:
    buf = f.read()

with open("output.txt", "w") as o:
    binary = bin(int.from_bytes(buf, byteorder='big'))[2:] # or byteorder='little' as necessary
    o.write(binary)

Beware that it might hog up memory when dealing with very large files.

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect, thank you so very much! What is the byte order?
Basically the way memory is stored...you can read about it. I'm not sure what is correct, but I always do big. stackoverflow.com/a/1346039
On Windows it's little endian.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.