Created
November 18, 2019 07:50
-
-
Save geekman/4529b5abb2458522494d17c4ef7cb1e2 to your computer and use it in GitHub Desktop.
hexdump to binary file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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