5
\$\begingroup\$

I need to calculate checksum using 16-bit ones' complement addition:

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, and if I understood the concept well (to add 16 bits), add the carry if any and then take the compliment.

Are there any improvements or corrections?

\$\endgroup\$

closed as off-topic by user673679, Edward, Graipher, Toby Speight, Sᴀᴍ Onᴇᴌᴀ Apr 11 at 15:44

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – user673679, Edward, Graipher, Toby Speight, Sᴀᴍ Onᴇᴌᴀ
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    \$\begingroup\$ What are the types of Word, Checksum and Buf? It looks like Word must be a uint32_t, Checksum a uint16_t and Buf a uint8_t*, buf the information really ought to be included in the question. \$\endgroup\$ – Toby Speight Apr 11 at 12:05
  • 1
    \$\begingroup\$ You'd get better reviews if you provided at least a whole, compilable function. \$\endgroup\$ – Edward Apr 11 at 13:06
4
\$\begingroup\$

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;
\$\endgroup\$
  • \$\begingroup\$ Ok I understand why it could be done at the end only, but I didnt understand 32k words thing. \$\endgroup\$ – harman Oct 3 '12 at 20:00
  • \$\begingroup\$ 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. \$\endgroup\$ – Doug Currie Oct 3 '12 at 21:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.