import sys datain = open(sys.argv[1], "r").readlines() dataout = [] TYPE_DATA = 0 TYPE_EOF = 1 def tohex(x): return hex(x)[2:].rjust(2,'0').upper() def fromhex(x): return int(x,16) for line in datain: if line[0] != ":": print("Invalid ihex file.") sys.exit(-1) count, address, type_, data, checksum = line[1:3], line[3:7], line[7:9], line[9:-2], line[-2:] count = fromhex(count) address = fromhex(address) type_ = fromhex(type_) checksum = fromhex(checksum) outline = line[:9] if type_ == TYPE_DATA: #print("Patching {} bytes at address {}".format(count, address)) bytes_ = [fromhex(data[x*2:x*2+2]) for x in range(count)] for i, x in enumerate(bytes_): #print(hex(i),hex(x),hex(address + 0x2d + i),hex(((address + 0x2d + i) & 0xff) ^ x)) bytes_[i] = ((address + 0x2d + i) & 0xff) ^ x outline += "".join([tohex(x) for x in bytes_]) checksum = 0 for x in range(1, len(outline) , 2): checksum += fromhex(outline[x:x+2]) checksum = (0x100 - (checksum & 0xff)) & 0xff outline += tohex(checksum) else: outline += line[9:].strip() dataout.append(outline) open(sys.argv[2], "w").write("\n".join(dataout))