Los
Los

Reputation: 11

Calculating a 16 bit checksum

I'm working with a program in C that reads in a file and then I have to do both 8 bit and 16 bit checksum for a program. I only have 8 bit checksum done so far.

I read the file and store the information in an array of characters and at end it takes the newline feed. For example, to calculate 8 bit check sum this is what happens essentially:

The file has 3 letters total (3 a's and a newline feed). So the array holds 4 chars, aaa + newline (97+97+97+10).

To my understanding I add all the bytes in the array, then do % 256, and that is my checksum.

97 * 3 = //3 a's (small a ) pulled from ascii table from what I understand

291 + 10 = 301 // + newline

301 % 256 = cc in hex //

However I am getting confused on how to calculate the 16 bit checksum, because I can't add 2 characters at a time if it's a single character array.

Upvotes: 0

Views: 22584

Answers (1)

Barmar
Barmar

Reputation: 782166

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 you're 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
int i;
for (i = 0; i < even_length; i += 2) {
    uint16_t val = array[i] + 256 * array[i+1];
    checksum += val;
}
if (i < length) { // Last byte if it's odd length
    checksum += array[i];
}

There's no need to use modulus, since unsigned integers implement modular arithmetic automatically.

Upvotes: 2

Related Questions