How is a 1s complement checksum useful for error detection?
Example, You have three words in UDP packet need to send.
0110011001100000
0101010101010101
1000111100001100
UDP at the sender side performs the 1s complement of the sum of all the 16-bit words. The sum of first two of these 16-bit words is
0110011001100000
+
0101010101010101
--> 1011101110110101
Adding the third word to the above sum gives, Note that this last addition had overflow, which was wrapped around
--> 0100101011000010
The 1s complement is obtained by converting all the 0s to 1s and converting all the 1s to 0s.
Thus the 1s complement of the sum 0100101011000010
is 1011010100111101
, which becomes the checksum. At the receiver, all four 16-bit words are added,including the checksum. If no errors are introduced into the packet, then clearly the sum at the receiver will be 1111111111111111
. If one of the bits is a 0, then we know that errors have been introduced into the packet.
I believe the example you're looking for can be found here.
The reason we do 1's complement is that when the 1's complement is added to the sum of all the values, and the result is trimmed to the bit-length of the machine (16 bits in the example above), it is all 1's. CPUs have a feature to take 1's complement of numbers, and taking the 1's complement of all-1 is all-0.
The reason: CPUs hate to work with bits except in chunks of however many it normally use. So adding two 64-bit numbers may take 1 cycle, but checking all the bits of that number individually will take many more (in a naive loop, perhaps as high as 8x64 cycles). CPUs also have capability to trivially take 1's complements, and detect that the result of the last calculation was zero without inspecting individual bits and branch based on that. So basically, it's an optimization that lets us check checksums really fast. Since most packets are just fine, this lets us check the checksum on the fly and get the data to the destination much faster.