一的补码(one's complement) 指的是正数=原码,负数=反码
而二的补码(two's complement) 指的就是通常所指的补码
IP checksum definition
The IP checksum is the 16 bit one's complement of the one's complement sum of all 16 bit words in the header.
One question many people may ask is "What is the 1's complement sum ?". This is because all computers utilize the 2's complement representation and the 1's complement is not used. The following gives a short introduction.
2's complement fixed point integers (8-bit)
Binary | Decimal | Hex | 0000 0000 | 0 | 00 | 0000 0001 | 1 | 01 | 0000 0010 | 2 | 02 | 0000 0011 | 3 | 03 | 1111 1111 | -1 | FF | 1111 1110 | -2 | FE | 1111 1101 | -3 | FD |
Let's add two intergers:
-3 + 5 = 2
FD + 05 = 01 02
Discarding the carry (01) gives the correct result.
1's complement fixed point integers (8-bit)
Binary | Decimal | Hex | 0000 0000 | 0 | 00 | 0000 0001 | 1 | 01 | 0000 0010 | 2 | 02 | 0000 0011 | 3 | 03 | 1111 1111 | -0 | FF | 1111 1110 | -1 | FE | 1111 1101 | -2 | FD | 1111 1100 | -3 | FC |
Add the same numbers:
-3 + 5 = 2
FC + 05 = 01 01
Adding the carry (01) to the LSB (01) gives the correct result:
01 + 01 = 02
So, the 1's complement sum is done by summing the numbers and adding the carry (or carries) to the result..
Simple Internet checksum example
Suppose we have an 8-bit, 2's complement, machine and send the packet
FE 05 00
where 00 is the checksum field.
Let's calculate and verify the Internet checksum.
FE + 05 = 01 03
This is the result of the normal (2's complement) addition. The 1's complement sum requires the addition of the carry to the 8-bit word (even though we will not get the same result)
03 + 01 = 04
so the 1's complement sum of FE + 05 is 04.
The 1's complement of the 1's complement sum (Internet checksum) will be
~04 = FB
and the packet will be sent as
FE 05 FB
Now, at the receiving end we add all the received bytes, including the checksum (again using the 2's complement representation)
FE + 05 + FB = 01 FE
The 1's complement sum is
FE + 01 = FF = -0
which checks that the transmission was OK (see below). |