When I read "TCP/IP explanation", I saw that the IP header checksum algorithm is called "sum of every 16 bits." So I thought that every part of the algorithm was first summed up. The write process is as follows: (take the following array as an example: Unsigned short a [10] = {0x4500, 0x059a, 0x82b9, 0X4000, 0x3206, 0x4f79, 0xa66f, 0x08ee, 0xc0a8, 0x0126}; because the first IP Minister 20b is 10 hexadecimal numbers, this is the verification part of the checksum)
- Unsigned short Re = 0;
- For (INT I = 0; I <10; I ++)
- Re + = ~ A [I];
- Re = ~ Re;
This is an incorrect practice. (I understand that "inverse code summation" is the first anticode addition before summation)
Then I made the following program:
- Unsigned short Re = 0;
- For (INT I = 0; I <10; I ++)
- Re + = A [I];
- Re = ~ Re;
This unsigend short is calculated based on the 16 power (65536) of model 2. The result calculation is still incorrect.
Then, I read the materials and made the following improvements:
- Int sum = 0;
- Unsigned short result = 0;
- For (INT I = 0; I <10; I ++)
- {
- Sum + = A [I];
- Sum = sum % 65535;
- }
- Result = (unsigned short) sum;
- Result = ~ Result;
This time, the result is 0 xFFFF, all 1, indicating that the checksum is correct.
It turns out that the decimal algorithm of this anticode is based on (2 to the Npower-1), that is, the 16-bit anti-code arithmetic is 65536-1 = 65535 (65536 is the 16 power of 2). Then, the above process is to "first obtain the part and then obtain its anti-code ", or, in turn, we can understand the "first-to-sum inverse code, then sum", that is, the reverse code summation.
The second program above is the addition operation of the unsinged short. The default value is the modulo 65536, so it is incorrect.
As for the first procedure, I had to learn Chinese and English well because of my misunderstanding.