Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute the checksum of an Intel Hex record in Python 3

The Intel Hex checksum algorithm is computed by adding a string of bytes. The last byte is the two's complement of the sum of the rest of the string, so adding it to a valid string should equal zero.

record_block is a byte array, read in like this:

file_handle = open("branson_weld_data.txt","rb")
ba = bytearray(file_handle.read())
# record_block is 20 20 00 00 00 3D 25 00 00 00 2B 02 00 85 01 00 31
# checksum is last byte, 31

I have not been successful in adding together the bytes of a Python byte list.

def verify_checksum(record_block):
    byte_sum = 0
    for byte in record_block:
        byte_sum &= b
    return byte_sum

print(verify_checksum(record_block))
    # should be zero

Is record_block a list of binary numbers? Am I adding bytes properly?

like image 673
ndemarco Avatar asked Dec 06 '25 17:12

ndemarco


1 Answers

This should give you the correct sum:

sum(record_block) & 0xff

but your example the checksum should be 'AB'

like image 182
Daniel Avatar answered Dec 08 '25 06:12

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!