Skip to content

Instantly share code, notes, and snippets.

@bNull
Created January 19, 2014 02:52
Show Gist options
  • Save bNull/8499878 to your computer and use it in GitHub Desktop.
Save bNull/8499878 to your computer and use it in GitHub Desktop.
import re
import binascii
import sys
def convert_hex(input_file, output_file):
""" input: list containing raw lines of hex
output: continuous binary data
"""
last_addr = None
for line in input_file:
addr = parse_prefix(line)
if addr == 0:
last_addr = addr
output_file.write(line_h2b(line))
elif (addr - last_addr) == 0x10:
last_addr = addr
output_file.write(line_h2b(line))
elif (addr - last_addr) > 0x10:
for null_addr in range((last_addr+0x10), (addr), 0x10):
output_file.write("\x00" * 0x10)
last_addr = addr
output_file.write(line_h2b(line))
else:
sys.exit("bad hex data? parsing line: %x" % addr)
def parse_prefix(line):
""" input: raw hex line, example:
0000: 0000 4400 0000 0000 0000 0000 0000 0000 ..D.............
output: integer value of the line location
"""
addr = re.search("^(\w\w\w\w):", line)
if addr:
return int(addr.group(1), 16)
else:
print "[DEBUG] no prefix addr returned: %s" % line
return None
def line_h2b(line):
""" input: raw hex line, example:
0000: 0000 4400 0000 0000 0000 0000 0000 0000 ..D.............
output: binary equivelant of the line of hex
"""
stripped_line = re.search("^\w{4}:\s*(\w{4}\s\w{4}\s\w{4}\s\w{4}\s\w{4}\s\w{4}\s\w{4}\s\w{4})\s*", line)
if stripped_line:
hex_data = re.sub(r'\s', "", stripped_line.group(1))
return binascii.a2b_hex(hex_data)
elif re.search("^\w{4}:\s*\*", line):
return "\x00" * 0x10
else:
return None
def main():
if len(sys.argv) < 3:
sys.exit("usage: %s <hex file> <binary output>" % sys.argv[0])
hex_f = open(sys.argv[1], 'rb')
bin_f = open(sys.argv[2], 'wb')
bindata = convert_hex(hex_f, bin_f)
hex_f.close()
bin_f.close()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment