Sub topic 4
Hamming Code and the Internet Checksum
Assume you know binary numbers, bitwise XOR, and the data link layer. This chapter shows how a Hamming code locates one wrong bit and how the Internet checksum detects corrupted data.
Hamming code: locating and correcting a single-bit error
A Hamming code adds parity bits to data. Number bit positions from 1, not 0. Put parity bits at positions that are powers of two: 1, 2, 4, 8, and so on. For four data bits, the Hamming(7,4) layout is:
| Position | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| Meaning | p1 | p2 | d1 | p4 | d2 | d3 | d4 |
Use even parity. Each parity bit checks positions whose binary position includes its bit:
| Check | Positions |
|---|---|
| p1 | 1, 3, 5, 7 |
| p2 | 2, 3, 6, 7 |
| p4 | 4, 5, 6, 7 |
For data 1011, place the data bits in positions 3, 5, 6, and 7:
p1 p2 1 p4 0 1 1Even parity gives p1 = 0, p2 = 1, and p4 = 0. The transmitted codeword is therefore 0110011.
If bit 6 changes during transmission, the receiver gets 0110001. It recomputes the three parity checks:
- Check p1: passes, so syndrome bit 1 is 0.
- Check p2: fails, so syndrome bit 2 is 1.
- Check p4: fails, so syndrome bit 4 is 1.
The syndrome is 1 + 2 + 4 = 6. Therefore, bit 6 is wrong. Flipping it restores the original codeword. Hamming(7,4) has minimum Hamming distance 3, so it corrects one-bit errors and detects two-bit errors.
The Internet checksum
The Internet checksum treats data as 16-bit words. The sender adds the words using ones' complement addition, which wraps any carry from bit 16 back into bit 0. It then complements every sum bit.
For example:
0x1234 + 0xF0F0 = 0x10324
wrap carry: 0x0324 + 1 = 0x0325
checksum: ~0x0325 = 0xFCDAThe receiver adds the data words and the checksum. A result of 0xFFFF indicates that the checksum test passed.
def internet_checksum(data: bytes) -> int:
if len(data) % 2:
data += b"\x00"
total = 0
for i in range(0, len(data), 2):
word = (data[i] << 8) | data[i + 1]
total += word
total = (total & 0xFFFF) + (total >> 16)
return ~total & 0xFFFF
print(f"{internet_checksum(bytes.fromhex('1234F0F0')):04X}") # FCDAThe checksum is simpler than a CRC but has weaker detection properties. Some different errors can cancel during addition, so protocols often use stronger checks at lower layers.
Exercise
A received Hamming(7,4) word has syndrome 5. Which bit should be corrected?
Show answer
Bit 5, because the syndrome value is the one-based position of the single erroneous bit.