将文件转换为二进制(生成十六进制转储)

4

我希望能够显示转换为二进制的文件,就像二进制编辑器一样。

例如,将PNG转换为89 50 4E 47 0D 0A 1A 0A 00 00 00....

f = open(path, "r")
print f.read() # I want to convert this to binary
f.close()

请给我建议。

2个回答

6

Python 3

要将二进制表示转换为十六进制:

bin_data = open(path, 'rb').read()
import codecs
hex_data = codecs.encode(bin_data, "hex_codec")

如果path指的是一个PNG文件,那么bin_data的前几个字节将看起来像\x89PNG\r\n,而hex_data的开头将看起来像89504e470d0a。为了使其格式化得好看一些,可以添加空格:
import re
hex_with_spaces =  re.sub('(..)', r'\1 ', hex_data)

hex_with_spaces的前几个字节将像89 50 4e 47 0d 0a这样。

作为codecs的替代方案,可以使用binascii

import binascii
hex_data = binascii.hexlify(bin_data)

查看jfs的答案,其中使用binascii提供了一个更详细的示例。

Python 2

要获得十六进制表示中的二进制:

bin_data = open(path, 'rb').read()
hex_data = bin_data.encode('hex')

如果path是指PNG文件,则bin_data的前几个字节将看起来像\x89PNG\r\n,而hex_data的开头将看起来像89504e470d0a。为了使其格式良好,请添加空格:
import re
hex_with_spaces =  re.sub('(..)', r'\1 ', hex_data)
hex_with_spaces 的前几个字节应该是这样的 89 50 4e 47 0d 0a

Python 3.7.2:AttributeError:'bytes'对象没有属性'encode' - Avión
1
@Avión 感谢您发现了这个问题。我刚刚更新了这个答案(写于2014年),以包括python3。 - John1024

2
为了同时支持Python 2和3,你可以使用binascii.hexlify()代替.encode('hex'):
#!/usr/bin/env python
"""Make a hexdump"""
import re
import sys
from binascii import hexlify
from functools import partial

def hexdump(filename, chunk_size=1<<15):
    add_spaces = partial(re.compile(b'(..)').sub, br'\1 ')
    write = getattr(sys.stdout, 'buffer', sys.stdout).write
    with open(filename, 'rb') as file:
        for chunk in iter(partial(file.read, chunk_size), b''):
            write(add_spaces(hexlify(chunk)))

hexdump(sys.argv[1])

注意:该文件以二进制模式打开,以避免由于文本文件启用换行符转换(例如'\r\n' -> '\n')而导致数据损坏。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接