Enhanced Internet checksum algorithm 8.10.20
For the principles, see:
Internet checksum algorithm: http://blog.csdn.net/microtong/archive/2008/10/20/3112139.aspx
Features of Internet checksum algorithm: http://blog.csdn.net/microtong/archive/2008/10/20/3112157.aspx
- /*
- Pbuffer is the start address of the datagram to be verified.
- Nsize specifies the length of the verification content, in bytes
- */
- Unsigned short checksum_calculating (unsigned short * pbuffer, int nsize)
- {
- Unsigned long dwcksum = 0; // 32-bit sum
- Unsigned char * P = (unsigned char *) & dwcksum;
- // Accumulate in two bytes
- While (nsize> 1)
- {
- Dwcksum + = * pbuffer ++;
- Printf ("/T %. 2x %. 2x %. 2x %. 2x/N ", * P, * (p + 1), * (p + 2), * (p + 3 ));
- Nsize-= sizeof (unsigned short );
- }
- Printf ("/T %. 2x %. 2x %. 2x %. 2x/N ", * P, * (p + 1), * (p + 2), * (p + 3 ));
- // If the total number of bytes is an odd number, add the last byte.
- If (nsize)
- {
- Dwcksum + = * (unsigned char *) pbuffer;
- Printf ("/T %. 2x %. 2x %. 2x %. 2x/N ", * P, * (p + 1), * (p + 2), * (p + 3 ));
- }
- // Accumulate the carry in the 32-bit integer high to the 16-bit lower
- While (dwcksum> 16 ){
- Dwcksum = (dwcksum & 0 xFFFF) + (dwcksum> 16 );
- Printf ("/T %. 2x %. 2x %. 2x %. 2x/N ", * P, * (p + 1), * (p + 2), * (p + 3 ));
- }
- // Obtain the inverse checksum.
- Dwcksum = ~ Dwcksum;
- Printf ("/T %. 2x %. 2x %. 2x %. 2x/N ", * P, * (p + 1), * (p + 2), * (p + 3 ));
- // Returns the 16-bit checksum.
- Return (unsigned short) (dwcksum );
- }