如何解析.bin到列表中?
问题描述:
我有一个.bin文件。我得到下面的输出,当我做进制打印如何解析.bin到列表中?
0000000 1ce7 0000 27d4 0006 0001 0251 202a 0100
0000010 0115 4067 6f09 0071 0071 0071 00c0 0100
0000020 0000 0000 0000 cf00 7750 2072 6e55 7469
....
我想分析这些字节,每个人存储在列表中。
['1c', 'e7', '00', '00', '27', 'd4'.....,'69']
我很困惑从哪里开始。我是否需要首先将.bin文件解析为文本文件,然后插入到列表中?
答
这应该对你有所帮助。
import binascii
filename = 'test.dat'
with open(filename, 'rb') as f:
content = f.read()
print(binascii.hexlify(content))
如果你想分开更多的只是附加到列表每2个十六进制。
编辑:下面的例子功能
def HexToByte(hexStr):
"""
Convert a string hex byte values into a byte string. The Hex Byte values may
or may not be space separated.
"""
# The list comprehension implementation is fractionally slower in this case
#
# hexStr = ''.join(hexStr.split(" "))
# return ''.join(["%c" % chr(int (hexStr[i:i+2],16)) \
# for i in range(0, len(hexStr), 2) ])
bytes = []
hexStr = ''.join(hexStr.split(" "))
for i in range(0, len(hexStr), 2):
bytes.append(chr(int (hexStr[i:i+2], 16)))
return ''.join(bytes)
答
要获得字节十六进制字符串列表:
>>> ['%02x' % d for d in bytearray(b'\x1c\xe7\x00\x00\x27\xd4')]
['1c', 'e7', '00', '00', '27', 'd4']
下面介绍如何从文件中读取的字节:
with open(filename, 'rb') as file:
data = file.read()
hex_list = ['%02x' % d for d in bytearray(data)]
在Python 3中,bytearray()
调用是可选的。
你为什么不试试? – ergonaut