A friend just popped up on MSN and asked me how to generate S19 checksums in Python. It's a pretty trivial bit of code, but I know I'll want it again, or maybe someone is out there googling for a way to do it, so here we go:
def s19_checksum(line):
length = int(line[2:4], 16)
bytes = [int(line[i*2:i*2+2], 16) for i in range(1, length+1)]
return ~sum(bytes) & 0xff
for s in ('S1130170707172737475767778797A7B7C7D7E7F03',
'S111FE7B59597B0173F6014A7B0146B7573093',
'S106FE891B823D98',
'S109F8020107DF01BA0D6C',):
print "* checksumming %s" % s
print " checksum: %s (compare with %s)" % (hex(s19_checksum(s)), s[-2:])
Update: Incorporated Michael Urman's suggestion. Previously I was using eval('0x' + line[i*2:i*2+2])
to parse hex numbers. Thanks Michael - I didn't know that int()
could do that!
Update 2: Fredrik Lundh points out a) that Python has a sum()
function to add up a list of numbers (better than my reduce((lambda a,b: a+b), bytes)
), and b) that s19_checksum()
calculates 0x4D for the last string, while the checksum included is 0x6C... this is actually the reason my friend contacted me. He had received a hex file with a suspected bad checksum (the 0x6C) and wanted to check it out :-)
... topic exchange: [