c – Calculating a 16 bit checksum?

c – Calculating a 16 bit checksum?

To calculate a 16-bit checksum, you process the array in increments of 2, and put one byte into the low-order byte of the value that youre adding, and the other byte into the high-order byte.

uint8_t array[MAX]; // The data gets copied into here
size_t length; // This is the length of the data
uint16_t checksum = 0;
size_t even_length = length - length%2; // Round down to multiple of 2
for (int i = 0; i < even_length; i += 2) {
    uint16_t val = array[i] + 256 * array[i+1];
    checksum += val;
}
if (i < length) { // Last byte if its odd length
    checksum += array[i];
}

Theres no need to use modulus, since unsigned integers implement modular arithmetic automatically.

c – Calculating a 16 bit checksum?

Leave a Reply

Your email address will not be published.