Search code examples
cchecksum

Calculating checksum (16 bit) in c


I am being asked to do a checksum on this text with the bit size being 16: "AAAAAAAAAA\nX"

At first the description seemed like it wanted the Fletcher-16 checksum. But the output of Fletcher's checksum performed on the above text yielded 8aee in hex. The example file says that the modular sum algorithm (minus the two's complement) should output 509d in hex.

The only other info is the standard "every two characters should be added to the checksum."

Besides using the generic Fletcher-16 checksum provided on the corresponding Wikipedia page, I have tried using this solution found here: calculating-a-16-bit-checksum to no avail. This code produced the hex value of 4f27.


Solution

  • Simply adding the data seeing it as an array of big-endian 16-bit integers produced the result 509d.

    #include <stdio.h>
    
    int main(void) {
        char data[] = "AAAAAAAAAA\nX";
        int sum = 0;
        int i;
        for(i = 0; data[i] != '\0' && data[i + 1] != '\0'; i += 2) {
            int value = ((unsigned char)data[i] << 8) | (unsigned char)data[i + 1];
            sum = (sum + value) & 0xffff;
        }
        printf("%04x\n", sum);
        return 0;
    }