Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
hexdump to binary file
#
# reconstructs binary files from hex dumps
# designed to be more forgiving than `xxd -r`
# dump formats are flexible, whether grouped by 4 digits,
# with or without ASCII, etc.
#
# 2019.10.24 darell tan
#
import sys
import re
from binascii import unhexlify
HEX_LINE = re.compile(r'^\s*[0-9a-f]{4,}:\s*[0-9a-f \t]{8,}', re.IGNORECASE)
linesize = 16
outf = open(sys.argv[1] + '.bin', 'wb')
assert outf
with open(sys.argv[1], 'r') as f:
last_addr = 0
line_no = 0
try:
for line in f:
line_no += 1
if not HEX_LINE.match(line): continue
line = line.replace(' ', '') # remove spaces
addr, data = line.split(':', 1)
addr = int(addr, 16)
assert addr != last_addr + linesize, \
'missing or corrupt lines. last addr: %08x, this: %08x' % \
(last_addr, addr)
line_data = unhexlify(data[:linesize * 2])
assert len(line_data) == linesize
outf.write(line_data)
last_addr += linesize
except:
print 'processing error at line %d: %s' % (line_no, sys.exc_info()[1])
print repr(line)
outf.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment