I have a .bin file. I get the following output when I do hexdump
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
....
I want to parse these bytes and store each of them in a list.
['1c', 'e7', '00', '00', '27', 'd4'.....,'69']
I'm confused at where to start. Do I need to parse the .bin file into text file first, and then insert into list?
This should help you.
import binascii
filename = 'test.dat'
with open(filename, 'rb') as f:
content = f.read()
print(binascii.hexlify(content))
After if you want to separate more just append to list every 2 hex.
EDIT: Here an example function
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 )