# 16 bit checksum calculation

I need to calculate checksum using 16 Bit ones complement addition. Here is the code:

``````while(byte>0)  //len = Total num of bytes
{
Word = ((Buf[i]<<8) + Buf[i+1]) + Checksum; //get two bytes at a time and  add previous calculated checsum value

Checksum = Word & 0x0FFFF; //Discard the carry if any

Word = (Word>>16);     //Keep the carryout for value exceeding 16 Bit

Checksum = Word + Checksum; //Add the carryout if any

len -= 2; //decrease by 2 for 2 byte boundaries
i += 2;
}

Checksum = (unsigned int)~Checksum;
``````

The above code works fine, if I understood the concept well ie to add 16 bits, add the carry if any and then take the compliment.

Any improvements or corrections in the program above?

-

If the packet size is less than 32k words, then you do not need to add the carry until the end:

``````while(byte>0)  //len = Total num of bytes
{
Checksum = ((Buf[i]<<8) + Buf[i+1]) + Checksum; //get two bytes at a time and  add previous calculated checsum value

len -= 2; //decrease by 2 for 2 byte boundaries
i += 2;
}

Checksum = (Checksum>>16) + Checksum; //Add the carryout

Checksum = (unsigned int)~Checksum;
``````
-
Ok I understand why it could be done at the end only, but I didnt understand 32k words thing. –  harman Oct 3 '12 at 20:00
If you have more than 32k 16-bit words, you can overflow a 32 bit integer when you add them up. With fewer than 32k words, you cannot overflow. –  Doug Currie Oct 3 '12 at 21:18