I see several issues in the code:
cp
is a pointer to zero ended char array holding the input message. Thewhile(*cp)
will have problem as inside the while loop bodycp
is incremented by 2!!! So it's fairly easy to skip the ending\0
of the char array (e.g. the input message has 2 characters) and result in a segmentation fault.*(cp)
and*(cp-1)
fetch the two neighbouring characters (bytes) in the input message. But why the two-bytes word is formed by*(cp-1)>>8 + *(cp)
? I think it would make sense to formed the 16bits word by*(cp-1)<<8 + *(cp)
i.e. the preceding character sits on the higher byte and the following character sits on the lower byte of the 16bits word.
To answer your question sum & 0xFFFF
just means calculating a number where the higher 16 bits are zero and the lower 16 bits are the same as in sum. the 0xFFFF
is a bit mask.
The funny thing is, even the above code might not doing the exact thing you mentioned as requirement, as long as the sending and receiving party are using the same piece of incorrect code, your checksum creation and verification will pass, as both ends are consistent with each other:)