【问题标题】:Read a file and write the file's binary to a text document读取文件并将文件的二进制文件写入文本文档
【发布时间】:2021-10-26 14:11:41
【问题描述】:

我正在使用 Python 3.10,我正在尝试读取 Windows 可执行文件,并将二进制数据以文本格式(1 和 0)输出到文本文件中。我只需要二进制文件,我不想要字节的偏移量和 ASCII 表示。我不想要任何空格或换行符。

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)

但是,它不起作用,我收到以下错误。

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

【问题讨论】:

  • 这是因为不可能将所有二进制字节都转换为 ASCII。
  • 例如,给定二进制 A\0(字母 A + NUL 字符),您希望文本文件中包含什么?
  • 我不想把它转换成 ASCII。我希望我的 HelloWorld.exe 程序转换为显示其二进制表示的文本文件。
  • (ASCII 是一个错字——抱歉。意思是 utf8。)你是不是像 hexdump 一样思考,比如od
  • 我希望我的 output.txt 文件包含 1010010101101000011101010101010101000111110101 作为示例。

标签: python python-3.x windows binaryfiles


【解决方案1】:

这段代码应该做你想做的:

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)

请注意,在处理非常大的文件时,它可能会占用内存。

【讨论】:

  • 完美,非常感谢!字节序是什么?
  • 基本上是内存的存储方式......你可以阅读它。我不确定什么是正确的,但我总是这样做bigstackoverflow.com/a/1346039
  • 在 Windows 上是小端。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多