Skip to content

Instantly share code, notes, and snippets.

@itdaniher
Created November 10, 2011 20:46
Show Gist options
  • Save itdaniher/1356164 to your computer and use it in GitHub Desktop.
Save itdaniher/1356164 to your computer and use it in GitHub Desktop.
Lightweight IHEX parser written in Python
#
# -----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# <[email protected]> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy us a beer in return.
#
# Ian Daniher, 2010-06-30
# based off of information contained at http://en.wikipedia.org/wiki/Intel_HEX
# -----------------------------------------------------------------------------
#
import sys
def checksum(val):
byte_sum = 0
byte = 0
i = 0
#if the input isn't an integer number of bytes, you're doing something wrong
if len(val) % 2 != 0:
print "input not of even length"
else:
#step through the bytes, summing them
while i < len(val):
byte = val[i:i+2]
byte_val = int(byte, 16)
byte_sum += byte_val
i += 2
#limit to the least significant byte
byte_sum = byte_sum & 0xff
#subtract least-significant-byte of the sum from 0x100
byte_sum = 0x100 - byte_sum
print hex(byte_sum)
lines = open(sys.argv[1],"r").readlines()
data = []
for n in range(len(lines)):
#the data-length is contained in the 1st-3rd nibbles
length=lines[n][1:3]
#the device address is contained in the 3rd-7th nibbles
#this corresponds directly to the flash address of our MCU
address=lines[n][3:7]
#the data type can be one of the following:
##00 - data record
##01 - end of file record
##02 - extended segment address record; segment base address if 2 bytes isn't enough
# to address all locations
##03 - start segment address record; initial segment base address
##04 - extended linear address record; allows 4-byte addressing
##05 - start linear address record
data_type=lines[n][7:9]
data_start = 9
data_end = 9 + int(length, 16)*2
data.append(lines[n][data_start:data_end])
calculated_checksum = lines[n][1:-4]
# val = lines[1][1:-4]
# checksum(val)
data = ''.join(data)
print "code size is %d bytes" % (len(data)/2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment