Search code examples
checksum8051

Checksum for a 32-bit integer


I'm trying to figure out how to do a checksum for a 32-bit integer (4 bytes).

It should reliably detect error in the number, and be as easy to compute as possible.

Ideas:

(bytes: a,b,c,d)

cksum = (((a xor b) xor c) xor d)
cksum = (((a / b) / c) / d)

Will this work for a simple checking, or should I try to implement something more "mainstream" like adler or crc? I just need to check if the number is OK, not to fix errors in it or anything like that. Ideally the checksum is 8 bits long.

I'm implementing this in assembly on 8051


Solution

  • A standard checksum works like this:

    • Add all the data bytes and drop down the carry,
    • Take the 2’s complement of total sum.

    To verify the checksum add all the data bytes including the checksum. If the result is not zero then some data have been corrupted.

    In C, you can do

    unsigned char checksum(unsigned char data[]){
        unsigned char sum = 0;
        int i;
        for(i=0; sizeof(data); i++){
            sum += data[i];
        }
        return ~sum + 1;
    }