Last active
September 4, 2024 14:01
-
-
Save speters/6703444 to your computer and use it in GitHub Desktop.
ihex crc recalculatorCalculates the checksums of lines in an ihex/intel hex file. Useful for patching a hex 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
#!/usr/bin/env python | |
# | |
# Intel HEX file CRC recalculator | |
# ihexcrc.py FILEWITHDAMAGEDCRC.HEX > NEWFILE.HEX | |
# | |
# See http://goodfet.sourceforge.net/dist/intelhex.py | |
# for a more elaborate version | |
# | |
from binascii import hexlify, unhexlify | |
import sys | |
if (len(sys.argv)) != 2: | |
print("Need IHEX file name as argument") | |
exit(1) | |
for s in open(sys.argv[1], 'r').readlines(): | |
s = s.rstrip('\r\n') | |
if not s: | |
next # empty line | |
if s[0] == ':': | |
try: | |
bin = bytearray(bytes.fromhex(s[1:])) | |
except TypeError: | |
pass | |
length = len(bin) | |
if length < 5: | |
raise RuntimeError | |
else: | |
raise RuntimeError | |
record_length = bin[0] | |
if length == (5 + record_length): | |
# w/ crc | |
oldcrc = bin.pop() | |
elif length == (4 + record_length): | |
# w/o crc | |
oldcrc = 0 | |
else: | |
raise RuntimeError | |
crc = (-sum(bin)) & 0x0FF | |
bin.append(crc) | |
print(':' + bin.hex().upper()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment