ndemarco
ndemarco

Reputation: 229

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?

Upvotes: 4

Views: 3029

Answers (1)

Daniel
Daniel

Reputation: 42748

This should give you the correct sum:

sum(record_block) & 0xff

but your example the checksum should be 'AB'

Upvotes: 1

Related Questions