At first, the private thought that the checksum is just a simple summation of the results, and later in TCP and UDP see the use of the checksum method is a bit strange-binary anti-code (cyclic carry) summation .
The cognitive process of human beings is bound to be from simple to complex, to see what this binary inverse code loop summation means. Example with 16 binary:
1. Reverse code for binary representation of the word1,word2...wordn of the checksum sequence
2. The inverse code sequence loop carry sum of the negation, the cyclic carrying sum means to add the sum to the low, may carry the X-bit, the number of the X-digit and the sum of the results of the 16-bit addition.
It feels like it's getting complicated. It doesn't matter, binary inverse loop carry sum has the following characteristics:
1. The summation process first seek the inverse code and then binary loop carry sum equivalent to the first binary loop carry sum and then the sum of the results of the negation code. (This greatly reduces the number of negation codes)
2. It has nothing to do with byte-order (big-endian problem) . (This may be the reason many protocols use this way to sum up)
1 ///@func: To caculate the Checksum of data2 ///@param: 1.nums:the number of sizeof (unsigned short int)3 ///4Unsigned Short intWordchecksum (const unsigned Short int*data, unsigned Short intnums)5 {6 Short intindex =0;7Unsignedintsum =0;8Unsigned Short intCheckSum;9 for(index =0; Index < nums;index++)Ten { OneSum + =Data[index]; A } - //cout << "The sum of data is:" << hex << sum << endl; -CheckSum = (unsigned Short int) (Sum &0xFFFF) + (unsigned Short int) (Sum >> -) ; the /*cout << "The CheckSum of data is:" << checkSum << Endl;*/ - return~CheckSum; -}
Test code:
WORD data1[5] = { 0x1122,0x1122,0x1122,0x1122,0x1122 }; WORD data2[5] = { 0x2211,0x2211,0x2211,0x2211,0x2211 }; cout<<"The CheckSum of Data1 is:"<< hex << wordchecksum (data1,5) <<Endl; cout<<"The CheckSum of Data2 is:"<< hex << wordchecksum (data2,5) << Endl;
Test results:
As can be seen, binary inverse code summation is independent of the byte order.
Checksum for "checksum" TCP and UDP