Computer Networks Module 3 – Data link layer: framing and error detection
Parity, checksums and Hamming codes
How parity bits, two-dimensional parity, the 16-bit Internet checksum and Hamming codes detect bit errors, and how a Hamming code corrects one.
What you will learn
- Compute single and two-dimensional parity and say which errors each detects
- Compute the 16-bit Internet checksum of RFC 1071 and verify a received header
- Use minimum Hamming distance to state how many errors a code detects and corrects
- Encode data with Hamming(7,4) and correct a single-bit error
Before you start
What you’ll learn · Before you start
What you will learn
- Compute single and two-dimensional parity and say which errors each detects
- Compute the 16-bit Internet checksum of RFC 1071 and verify a received header
- Use minimum Hamming distance to state how many errors a code detects and corrects
- Encode data with Hamming(7,4) and correct a single-bit error
Before you start
On this page
Four data bits become seven positions in Hamming(7,4), allowing a receiver to correct one flipped bit. Two flipped bits can make that same decoder return the wrong data. Error-detecting codes add redundant bits so that specified damage breaks a relation the receiver can test. A parity bit checks whether the number of ones is even. Two-dimensional parity checks rows and columns. The 16-bit Internet checksum adds words with end-around carry. A Hamming code places several parity checks so their failed positions form a syndrome. This lesson shows their core algorithms in the leading languages, measures selected error patterns with Python, and uses minimum distance to separate what a validity check can detect from what a correcting decoder can safely repair.
Even parity detects odd numbers of flipped bits
With code validity check: A test that a received word belongs to a permitted code; a passing relation can still result from an undetected error that reaches another valid word., the sender adds one bit chosen so that the total number of 1s is even; the receiver counts the 1s again and rejects the data if the count is odd. (Odd parity, the same idea with an odd count, is also used.) One flipped bit makes the count odd, and so does any odd number of flipped bits. Two flipped bits, or any even number, leave it even:
"""One even-parity bit on the 7-bit code of the letter K: one flipped bit is caught, two are not."""
def even_parity(bits):
"""The bit that makes the number of 1s even."""
return sum(bits) % 2
k = [1, 0, 0, 1, 0, 1, 1] # "K" is 1001011: four 1s, so its parity bit is 0
sent = k + [even_parity(k)]
one_flip = sent.copy()
one_flip[2] ^= 1
two_flips = one_flip.copy()
two_flips[5] ^= 1
for name, word in [("sent", sent), ("one bit flipped", one_flip), ("two bits flipped", two_flips)]:
print(f"{name:17} {''.join(map(str, word))} parity check {'passes' if sum(word) % 2 == 0 else 'FAILS'}") Output
sent 10010110 parity check passes one bit flipped 10110110 parity check FAILS two bits flipped 10110010 parity check passes
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 parity.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Python 3.14 · main.py
def even_parity(bits: list[int]) -> int:
return sum(bits) % 2
data = [1, 0, 0, 1, 0, 1, 1]
sent = data + [even_parity(data)]
one_flip = sent.copy()
one_flip[2] ^= 1
two_flips = one_flip.copy()
two_flips[5] ^= 1
for name, word in [
("sent", sent),
("one bit flipped", one_flip),
("two bits flipped", two_flips),
]:
check = "passes" if sum(word) % 2 == 0 else "FAILS"
print(f"{name:17} {''.join(map(str, word))} parity check {check}") Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py
JavaScript Node 24 · main.mjs
function evenParity(bits) {
return bits.reduce((total, bit) => total + bit, 0) % 2;
}
const data = [1, 0, 0, 1, 0, 1, 1];
const sent = [...data, evenParity(data)];
const oneFlip = [...sent];
oneFlip[2] ^= 1;
const twoFlips = [...oneFlip];
twoFlips[5] ^= 1;
for (const [name, word] of [
["sent", sent],
["one bit flipped", oneFlip],
["two bits flipped", twoFlips],
]) {
const check = evenParity(word) === 0 ? "passes" : "FAILS";
console.log(`${name.padEnd(17)} ${word.join("")} parity check ${check}`);
} Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs
Java 25 LTS · Main.java
import java.util.Arrays;
import java.util.Locale;
public class Main {
static int evenParity(int[] bits) {
return Arrays.stream(bits).sum() % 2;
}
static String bitString(int[] bits) {
var out = new StringBuilder();
for (int bit : bits) {
out.append(bit);
}
return out.toString();
}
public static void main(String[] args) {
Locale.setDefault(Locale.ROOT);
int[] data = {1, 0, 0, 1, 0, 1, 1};
int[] sent = Arrays.copyOf(data, data.length + 1);
sent[data.length] = evenParity(data);
int[] oneFlip = sent.clone();
oneFlip[2] ^= 1;
int[] twoFlips = oneFlip.clone();
twoFlips[5] ^= 1;
String[] names = {"sent", "one bit flipped", "two bits flipped"};
int[][] cases = {sent, oneFlip, twoFlips};
for (int i = 0; i < cases.length; i++) {
String check = evenParity(cases[i]) == 0 ? "passes" : "FAILS";
System.out.printf("%-17s %s parity check %s%n", names[i], bitString(cases[i]), check);
}
}
} Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java
C++23 · main.cpp
#include <numeric>
#include <print>
#include <span>
#include <string>
#include <utility>
#include <vector>
int even_parity(std::span<const int> bits) {
return std::accumulate(bits.begin(), bits.end(), 0) % 2;
}
std::string bit_string(std::span<const int> bits) {
std::string result;
for (const int bit : bits) {
result += static_cast<char>('0' + bit);
}
return result;
}
int main() {
const std::vector<int> data = {1, 0, 0, 1, 0, 1, 1};
auto sent = data;
sent.push_back(even_parity(data));
auto one_flip = sent;
one_flip[2] ^= 1;
auto two_flips = one_flip;
two_flips[5] ^= 1;
const std::vector<std::pair<std::string, std::vector<int>>> cases = {
{"sent", sent},
{"one bit flipped", one_flip},
{"two bits flipped", two_flips}};
for (const auto &[name, word] : cases) {
const auto check = even_parity(word) == 0 ? "passes" : "FAILS";
std::println("{:<17} {} parity check {}", name, bit_string(word), check);
}
} Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main
C# 14 · .NET 10 · app.cs
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
int[] data = [1, 0, 0, 1, 0, 1, 1];
int[] sent = [.. data, EvenParity(data)];
int[] oneFlip = [.. sent];
oneFlip[2] ^= 1;
int[] twoFlips = [.. oneFlip];
twoFlips[5] ^= 1;
(string Name, int[] Word)[] cases =
[
("sent", sent),
("one bit flipped", oneFlip),
("two bits flipped", twoFlips)
];
foreach (var (name, word) in cases)
{
var check = EvenParity(word) == 0 ? "passes" : "FAILS";
Console.WriteLine($"{name,-17} {string.Concat(word)} parity check {check}");
}
static int EvenParity(int[] bits) => bits.Sum() % 2; Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs
C23 · main.c
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static unsigned even_parity(const uint8_t *bits, size_t count) {
unsigned total = 0;
for (size_t i = 0; i < count; ++i) {
total += bits[i];
}
return total % 2;
}
int main(void) {
const uint8_t data[7] = {1, 0, 0, 1, 0, 1, 1};
uint8_t sent[8];
memcpy(sent, data, sizeof data);
sent[7] = (uint8_t)even_parity(data, 7);
uint8_t one_flip[8], two_flips[8];
memcpy(one_flip, sent, sizeof sent);
one_flip[2] ^= 1;
memcpy(two_flips, one_flip, sizeof one_flip);
two_flips[5] ^= 1;
const char *names[] = {"sent", "one bit flipped", "two bits flipped"};
const uint8_t *cases[] = {sent, one_flip, two_flips};
for (size_t i = 0; i < 3; ++i) {
char word[9];
for (size_t j = 0; j < 8; ++j) {
word[j] = (char)('0' + cases[i][j]);
}
word[8] = '\0';
const char *check = even_parity(cases[i], 8) == 0 ? "passes" : "FAILS";
printf("%-17s %s parity check %s\n", names[i], word, check);
}
return 0;
} Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main
PHP 8.5 · main.php
<?php
declare(strict_types=1);
/** @param list<int> $bits */
function evenParity(array $bits): int
{
return array_sum($bits) % 2;
}
$data = [1, 0, 0, 1, 0, 1, 1];
$sent = [...$data, evenParity($data)];
$oneFlip = $sent;
$oneFlip[2] ^= 1;
$twoFlips = $oneFlip;
$twoFlips[5] ^= 1;
$cases = [
['sent', $sent],
['one bit flipped', $oneFlip],
['two bits flipped', $twoFlips],
];
foreach ($cases as [$name, $word]) {
$check = evenParity($word) === 0 ? 'passes' : 'FAILS';
printf("%-17s %s parity check %s\n", $name, implode('', $word), $check);
} Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php
Rust 1.99 · main.rs
fn even_parity(bits: &[u8]) -> u8 {
bits.iter().sum::<u8>() % 2
}
fn bit_string(bits: &[u8]) -> String {
bits.iter().map(|bit| char::from(b'0' + bit)).collect()
}
fn main() {
let data = vec![1, 0, 0, 1, 0, 1, 1];
let mut sent = data.clone();
sent.push(even_parity(&data));
let mut one_flip = sent.clone();
one_flip[2] ^= 1;
let mut two_flips = one_flip.clone();
two_flips[5] ^= 1;
for (name, word) in [
("sent", sent),
("one bit flipped", one_flip),
("two bits flipped", two_flips),
] {
let check = if even_parity(&word) == 0 {
"passes"
} else {
"FAILS"
};
println!("{name:<17} {} parity check {check}", bit_string(&word));
}
} Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main
TypeScript 6.0 · main.ts
function evenParity(bits: readonly number[]): number {
return bits.reduce((total, bit) => total + bit, 0) % 2;
}
const data = [1, 0, 0, 1, 0, 1, 1];
const sent = [...data, evenParity(data)];
const oneFlip = [...sent];
oneFlip[2] = (oneFlip[2] ?? 0) ^ 1;
const twoFlips = [...oneFlip];
twoFlips[5] = (twoFlips[5] ?? 0) ^ 1;
const cases: [string, number[]][] = [
["sent", sent],
["one bit flipped", oneFlip],
["two bits flipped", twoFlips],
];
for (const [name, word] of cases) {
const check = evenParity(word) === 0 ? "passes" : "FAILS";
console.log(`${name.padEnd(17)} ${word.join("")} parity check ${check}`);
} Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts
Go 1.27 · main.go
package main
import "fmt"
func evenParity(bits []int) int {
total := 0
for _, bit := range bits {
total += bit
}
return total % 2
}
func bitString(bits []int) string {
result := make([]byte, len(bits))
for i, bit := range bits {
result[i] = byte('0' + bit)
}
return string(result)
}
func main() {
data := []int{1, 0, 0, 1, 0, 1, 1}
sent := append(append([]int(nil), data...), evenParity(data))
oneFlip := append([]int(nil), sent...)
oneFlip[2] ^= 1
twoFlips := append([]int(nil), oneFlip...)
twoFlips[5] ^= 1
cases := []struct {
name string
word []int
}{
{"sent", sent},
{"one bit flipped", oneFlip},
{"two bits flipped", twoFlips},
}
for _, item := range cases {
check := "FAILS"
if evenParity(item.word) == 0 {
check = "passes"
}
fmt.Printf("%-17s %s parity check %s\n", item.name, bitString(item.word), check)
}
} Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go
Swift 6.4 · main.swift
func evenParity(_ bits: [Int]) -> Int {
bits.reduce(0, +) % 2
}
func pad(_ text: String, to width: Int) -> String {
text + String(repeating: " ", count: max(0, width - text.count))
}
let data = [1, 0, 0, 1, 0, 1, 1]
let sent = data + [evenParity(data)]
var oneFlip = sent
oneFlip[2] ^= 1
var twoFlips = oneFlip
twoFlips[5] ^= 1
for (name, word) in [
("sent", sent),
("one bit flipped", oneFlip),
("two bits flipped", twoFlips),
] {
let check = evenParity(word) == 0 ? "passes" : "FAILS"
let bits = word.map { String($0) }.joined()
print("\(pad(name, to: 17)) \(bits) parity check \(check)")
} Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main
Ruby 4.0 · main.rb
# frozen_string_literal: true
def even_parity(bits)
bits.sum % 2
end
data = [1, 0, 0, 1, 0, 1, 1]
sent = data + [even_parity(data)]
one_flip = sent.dup
one_flip[2] ^= 1
two_flips = one_flip.dup
two_flips[5] ^= 1
cases = [
['sent', sent],
['one bit flipped', one_flip],
['two bits flipped', two_flips]
]
cases.each do |name, word|
check = even_parity(word).zero? ? 'passes' : 'FAILS'
puts "#{name.ljust(17)} #{word.join} parity check #{check}"
end Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb
Kotlin 2.4 · Main.kt
fun evenParity(bits: IntArray): Int = bits.sum() % 2
fun main() {
val data = intArrayOf(1, 0, 0, 1, 0, 1, 1)
val sent = data + evenParity(data)
val oneFlip = sent.copyOf()
oneFlip[2] = oneFlip[2] xor 1
val twoFlips = oneFlip.copyOf()
twoFlips[5] = twoFlips[5] xor 1
val cases =
listOf(
"sent" to sent,
"one bit flipped" to oneFlip,
"two bits flipped" to twoFlips,
)
for ((name, word) in cases) {
val check = if (evenParity(word) == 0) "passes" else "FAILS"
println("${name.padEnd(17)} ${word.joinToString("")} parity check $check")
}
} Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar
Dart 3.13 · main.dart
int evenParity(List<int> bits) => bits.fold(0, (total, bit) => total + bit) % 2;
void main() {
final data = [1, 0, 0, 1, 0, 1, 1];
final sent = [...data, evenParity(data)];
final oneFlip = [...sent];
oneFlip[2] ^= 1;
final twoFlips = [...oneFlip];
twoFlips[5] ^= 1;
for (final (name, word) in [
('sent', sent),
('one bit flipped', oneFlip),
('two bits flipped', twoFlips),
]) {
final check = evenParity(word) == 0 ? 'passes' : 'FAILS';
print('${name.padRight(17)} ${word.join()} parity check $check');
}
} Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart
What every language printed
sent 10010110 parity check passes one bit flipped 10110110 parity check FAILS two bits flipped 10110010 parity check passes
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. Runs on this device: a JavaScript build of this program (about 65 KB), made when the page was built. The first run also downloads the JavaScript runner (about 0.6 MB), which is kept for the next runs. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 151 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a .NET build of this program (about 3 KB), made when the page was built. The first run also downloads .NET (about 3.6 MB), which is kept for the next runs. Edit runs your changes in the browser: the first edited run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 8 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads PHP (about 4.3 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 20 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads the JavaScript runner (about 0.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 715 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 1.7 MB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads Ruby (about 10.2 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 181 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 10 KB), made when the page was built. To change the code, copy it and run it with the command below.Your run, in this browser
The 7-bit code of the letter K gets its parity bit, and of the two damaged copies, the one with one flipped bit is caught and the one with two is not. Among equally likely nonzero masks of an n-bit codeword, exactly 2^(n−1)−1 have even weight, a fraction approaching one half as n grows. This is a counting model, not an observed error rate for every link. That is acceptable only where errors are rare and come one at a time, and it is why parity alone protects so little on a network link.
Compare the original one-flip failure with the two-flip accepted word before treating parity as an integrity relation.
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- The original seven data bits contain four ones, so even parity appends a zero and sends 10010110.
- The original one-flip record has an odd number of ones and the even-parity relation fails.
- The original two-flip record returns to even weight and passes the parity relation, despite changed data.
Checkpoint
Check: Even parity detects odd numbers of flipped bits
Row and column checks locate one flipped bit
Arrange the data in a block, add a parity bit to every row and a parity bit to every column (a last bit, in the corner, checks the parity bits themselves), and a single flipped bit makes exactly one row and one column fail. The receiver flips the bit where they cross:
Two-dimensional parity points at the damaged bit
Text description of the diagram
The diagram shows the 4 x 4 block of data bits from parity.py as it arrives, after one data bit was damaged. A parity bit ends each row, a row of column parities runs along the bottom (the parity bits have dashed borders), and the checks are written beside the last column and under the last row.
- The rows, as received, are 1 0 1 1 1, then 0 1 0 0 0, then 1 1 0 1 1, then 0 0 1 0 1, and the column-parity row 0 0 1 0 1.
- The damaged bit is in the second row and the third column: it was sent as 1 and arrived as 0, and it has a thick double border.
- Every row check says ok except the second row's, which fails; every column check says ok except the third column's, which fails.
- The failing row and the failing column cross at the damaged bit, so the receiver can flip it back.
"""Two-dimensional parity on a 4 x 4 block of bits: find and fix one flipped bit, then try every 1- to 4-bit error."""
from itertools import combinations
def even_parity(bits):
return sum(bits) % 2
def add_parity(rows):
"""Append a parity bit to each row, then a row of column parities (its last bit checks both)."""
rows = [r + [even_parity(r)] for r in rows]
return rows + [[even_parity(col) for col in zip(*rows)]]
def failing(block):
"""The rows and the columns whose parity no longer checks."""
bad_rows = [i for i, r in enumerate(block) if sum(r) % 2]
bad_cols = [j for j, c in enumerate(zip(*block)) if sum(c) % 2]
return bad_rows, bad_cols
data = [[1, 0, 1, 1], [0, 1, 1, 0], [1, 1, 0, 1], [0, 0, 1, 0]]
block = add_parity(data)
print("block with parity:", ["".join(map(str, r)) for r in block])
block[1][2] ^= 1 # one bit of the data is hit by noise
rows, cols = failing(block)
print("one flip: rows", rows, "and columns", cols, "fail, so the bad bit is", (rows[0], cols[0]))
block[rows[0]][cols[0]] ^= 1 # flip it back: corrected
block[0][0] ^= 1
block[0][3] ^= 1 # two flips in one row
rows, cols = failing(block)
print("two flips in one row: rows", rows, "and columns", cols, "fail: detected, but not located")
block[0][0] ^= 1
block[0][3] ^= 1
# Every pattern of 1 to 4 flipped bits among the 25 bits, and how many of them the checks miss.
cells = [(i, j) for i in range(5) for j in range(5)]
print()
for n in range(1, 5):
missed = total = 0
for flips in combinations(cells, n):
for i, j in flips:
block[i][j] ^= 1
total += 1
missed += failing(block) == ([], [])
for i, j in flips:
block[i][j] ^= 1
print(f"{n} bit{'s' if n > 1 else ' '} flipped: {total:6,} patterns, {missed:3} undetected") Output
block with parity: ['10111', '01100', '11011', '00101', '00101'] one flip: rows [1] and columns [2] fail, so the bad bit is (1, 2) two flips in one row: rows [] and columns [0, 3] fail: detected, but not located 1 bit flipped: 25 patterns, 0 undetected 2 bits flipped: 300 patterns, 0 undetected 3 bits flipped: 2,300 patterns, 0 undetected 4 bits flipped: 12,650 patterns, 100 undetected
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 two_d_parity.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
The program finds the flipped bit of the diagram from the failing row and column, flips it back, and then shows what two-dimensional parity cannot do. Two flips in the same row leave that row’s parity even, but two columns fail: the error is detected but cannot be located. And the program tried every one of the 15,275 patterns of one to four flipped bits among the 25 bits: all 2,625 patterns of one, two or three flips were detected, and only 100 of the 12,650 four-bit patterns got through. Those 100 are the corners of rectangles: two flips in each of two rows, in the same two columns, keep every row and every column even. Choose 2 rows of 5 and 2 columns of 5 and you get 10 × 10 = 100.
The cost is 9 parity bits for 16 data bits. Two-dimensional parity shows the idea behind error correction (enough independent checks pin a bad bit down), but it pays far more redundant bits for each corrected bit than the codes below.
Locate one bit with the failed row/column, then compare the 100 original undetected rectangle masks.
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- The original 4-by 4 payload receives four row checks, four column checks and one corner check.
- Under the single-error assumption, the failing row and column identify the changed bit.
- The exhaustive original 25-bit codeword run finds 100 undetected four-flip rectangles among 12650 four-bit masks.
Checkpoint
Check: Row and column checks locate one flipped bit
Minimum distance bounds detection and correction
The Hamming distance between two words of the same length is the number of positions in which they differ: 0110011 and 0100011 are at distance 1, while 0110011 and 1110000 are at distance 3. A code is a set of allowed words, its codewords, and its minimum code distance: The fewest differing positions between two distinct permitted codewords, used to derive detection and nearest-decoding bounds under stated error assumptions. d is the smallest distance between any two of them. From d alone you can read off what the code can do:
The minimum-distance reasoning in the cited Hamming paper is short. Fewer than d flips can never turn one codeword into another, so the damage always shows. And if at most t bits flip with 2t + 1 ≤ d, the received word is still closer to the codeword that was sent than to any other, so the receiver can correct it by choosing the nearest codeword. The program below finds d for three small codes by comparing every pair of codewords:
"""Minimum Hamming distance of three small codes, found by comparing every pair of codewords."""
from itertools import combinations, product
def distance(a, b):
"""How many positions two words of the same length differ in."""
return sum(x != y for x, y in zip(a, b))
def hamming74(d1, d2, d3, d4):
"""Hamming(7,4): positions 1 to 7 hold p1 p2 d1 p4 d2 d3 d4, with even parity."""
return (d1 ^ d2 ^ d4, d1 ^ d3 ^ d4, d1, d2 ^ d3 ^ d4, d2, d3, d4)
codes = {
"3 data bits + 1 parity bit": [bits + (sum(bits) % 2,) for bits in product((0, 1), repeat=3)],
"1 bit sent three times": [(b, b, b) for b in (0, 1)],
"Hamming(7,4)": [hamming74(*bits) for bits in product((0, 1), repeat=4)],
}
print("0110011 vs 0100011:", distance("0110011", "0100011"))
print("0110011 vs 1110000:", distance("0110011", "1110000"))
print()
for name, code in codes.items():
d = min(distance(a, b) for a, b in combinations(code, 2))
print(f"{name}: {len(code)} codewords, minimum distance {d}: detects {d - 1}, corrects {(d - 1) // 2}") Output
0110011 vs 0100011: 1 0110011 vs 1110000: 3 3 data bits + 1 parity bit: 8 codewords, minimum distance 2: detects 1, corrects 0 1 bit sent three times: 2 codewords, minimum distance 3: detects 2, corrects 1 Hamming(7,4): 16 codewords, minimum distance 3: detects 2, corrects 1
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 distance.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
A parity bit gives d = 2: it detects one error and corrects none. Sending each bit three times gives d = 3 and lets the receiver take a majority vote, at the cost of three bits for every data bit. Hamming(7,4) also reaches d = 3, with only 3 check bits for every 4 data bits. Two-dimensional parity from the section above has d = 4, which is why its smallest undetected errors had four flipped bits. A validity check detects up to three; a guaranteed nearest-codeword correction handles one, and stronger damage needs its own decoder policy.
Detecting and correcting compete for the same distance. A code with d = 3 can either correct one error, or detect up to two, but not both at once: a receiver that corrects every single-bit error will silently “correct” a two-bit error into the wrong codeword, as the next section shows.
Read the detection and nearest-decoding bounds separately on the original distance 2,3 and 4 code families.
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- Minimum distance counts the fewest differing positions between two allowed codewords.
- Fewer than d flips cannot change one codeword into another, so code membership rejects those changed words.
- A guaranteed nearest-codeword correction needs the sent word to remain closer than every other codeword; its error model must be stated.
Checkpoint
Check: Minimum distance bounds detection and correction
A Hamming syndrome locates a single-bit error
Hamming’s construction numbers the positions of a codeword from 1 and puts check bits at the positions that are powers of two, 1, 2 and 4; the data bits fill positions 3, 5, 6 and 7. Each check bit gives even parity over the positions whose number has its bit set in binary. In the table, the last three columns say whether p1, p2 or p4 checks each position:
| Position | Details |
|---|---|
| 1 (001) | Holds: p1; p1: yes; p2: no; p4: no |
| 2 (010) | Holds: p2; p1: no; p2: yes; p4: no |
| 3 (011) | Holds: d1; p1: yes; p2: yes; p4: no |
| 4 (100) | Holds: p4; p1: no; p2: no; p4: yes |
| 5 (101) | Holds: d2; p1: yes; p2: no; p4: yes |
| 6 (110) | Holds: d3; p1: no; p2: yes; p4: yes |
| 7 (111) | Holds: d4; p1: yes; p2: yes; p4: yes |
| The receiver repeats the three checks. Each failing check contributes its own weight, 1, 2 or 4, and the sum, called | |
| the Hamming syndrome: The combined outcomes of a Hamming code's parity checks; under its single-bit error assumption, the syndrome identifies the position to correct., is the position of the flipped bit: a bit at position 6 (binary 110) is covered by p2 and p4, so | |
| exactly those two checks fail and 2 + 4 = 6. An equivalent shortcut is to XOR together the position numbers of all | |
| the 1s in the word, which gives 0 for a correct codeword. |
"""Hamming(7,4): encode 4 data bits, flip each of the 7 bits in turn, and let the syndrome point at it."""
def encode(data):
"""'1011' -> '0110011': positions 1 to 7 are p1 p2 d1 p4 d2 d3 d4, with even parity."""
d1, d2, d3, d4 = (int(c) for c in data)
p1 = d1 ^ d2 ^ d4 # checks positions 1, 3, 5, 7 (bit value 1 set in the position number)
p2 = d1 ^ d3 ^ d4 # checks positions 2, 3, 6, 7 (bit value 2 set)
p4 = d2 ^ d3 ^ d4 # checks positions 4, 5, 6, 7 (bit value 4 set)
return "".join(map(str, (p1, p2, d1, p4, d2, d3, d4)))
def syndrome(word):
"""The position (1 to 7) of a single flipped bit, or 0 when every check passes."""
s = 0
for position in range(1, 8):
if word[position - 1] == "1":
s ^= position # the XOR of the positions of all 1s
return s
def decode(word):
"""Correct up to one flipped bit, then return the 4 data bits."""
s = syndrome(word)
if s:
bits = list(word)
bits[s - 1] = "1" if bits[s - 1] == "0" else "0"
word = "".join(bits)
return word[2] + word[4] + word[5] + word[6]
def flip(word, *positions):
bits = list(word)
for p in positions:
bits[p - 1] = "1" if bits[p - 1] == "0" else "0"
return "".join(bits)
sent = encode("1011")
print("data 1011 is sent as", sent, "with syndrome", syndrome(sent))
for p in range(1, 8):
received = flip(sent, p)
print(f"bit {p} flipped: {received} syndrome {syndrome(received)} ({syndrome(received):03b}) decoded {decode(received)}")
two = flip(sent, 2, 6)
print(f"\nbits 2 and 6 flipped: {two} syndrome {syndrome(two)} decoded {decode(two)} (wrong: two errors look like one)") Output
data 1011 is sent as 0110011 with syndrome 0 bit 1 flipped: 1110011 syndrome 1 (001) decoded 1011 bit 2 flipped: 0010011 syndrome 2 (010) decoded 1011 bit 3 flipped: 0100011 syndrome 3 (011) decoded 1011 bit 4 flipped: 0111011 syndrome 4 (100) decoded 1011 bit 5 flipped: 0110111 syndrome 5 (101) decoded 1011 bit 6 flipped: 0110001 syndrome 6 (110) decoded 1011 bit 7 flipped: 0110010 syndrome 7 (111) decoded 1011 bits 2 and 6 flipped: 0010001 syndrome 4 decoded 1001 (wrong: two errors look like one)
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 hamming74.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Python 3.14 · main.py
def encode(data: str) -> str:
first, second, third, fourth = map(int, data)
bits = (
first ^ second ^ fourth,
first ^ third ^ fourth,
first,
second ^ third ^ fourth,
second,
third,
fourth,
)
return "".join(map(str, bits))
def syndrome(word: str) -> int:
result = 0
for position, bit in enumerate(word, 1):
if bit == "1":
result ^= position
return result
def flip(word: str, positions: list[int]) -> str:
bits = list(word)
for position in positions:
bits[position - 1] = "1" if bits[position - 1] == "0" else "0"
return "".join(bits)
def decode(word: str) -> str:
position = syndrome(word)
corrected = flip(word, [position]) if position else word
return "".join(corrected[index] for index in (2, 4, 5, 6))
sent = encode("1011")
print(f"data 1011 is sent as {sent} with syndrome {syndrome(sent)}")
for position in range(1, 8):
received = flip(sent, [position])
result = syndrome(received)
print(
f"bit {position} flipped: {received} syndrome {result} "
f"({result:03b}) decoded {decode(received)}"
)
two = flip(sent, [2, 6])
print(
f"\nbits 2 and 6 flipped: {two} syndrome {syndrome(two)} "
f"decoded {decode(two)} (wrong: two errors look like one)"
) Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py
JavaScript Node 24 · main.mjs
function encode(data) {
const [first, second, third, fourth] = [...data].map(Number);
return [
first ^ second ^ fourth,
first ^ third ^ fourth,
first,
second ^ third ^ fourth,
second,
third,
fourth,
].join("");
}
function syndrome(word) {
let result = 0;
for (let index = 0; index < word.length; index++) {
if (word[index] === "1") result ^= index + 1;
}
return result;
}
function flip(word, positions) {
const bits = [...word];
for (const position of positions) {
bits[position - 1] = bits[position - 1] === "0" ? "1" : "0";
}
return bits.join("");
}
function decode(word) {
const position = syndrome(word);
const corrected = position ? flip(word, [position]) : word;
return [2, 4, 5, 6].map((index) => corrected[index]).join("");
}
const sent = encode("1011");
console.log(`data 1011 is sent as ${sent} with syndrome ${syndrome(sent)}`);
for (let position = 1; position <= 7; position++) {
const received = flip(sent, [position]);
const result = syndrome(received);
console.log(
`bit ${position} flipped: ${received} syndrome ${result} ` +
`(${result.toString(2).padStart(3, "0")}) decoded ${decode(received)}`,
);
}
const two = flip(sent, [2, 6]);
console.log(
`\nbits 2 and 6 flipped: ${two} syndrome ${syndrome(two)} ` +
`decoded ${decode(two)} (wrong: two errors look like one)`,
); Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs
Java 25 LTS · Main.java
public class Main {
static String encode(String data) {
int first = data.charAt(0) - '0', second = data.charAt(1) - '0';
int third = data.charAt(2) - '0', fourth = data.charAt(3) - '0';
int[] bits = {
first ^ second ^ fourth,
first ^ third ^ fourth,
first,
second ^ third ^ fourth,
second,
third,
fourth
};
var word = new StringBuilder();
for (int bit : bits) {
word.append(bit);
}
return word.toString();
}
static int syndrome(String word) {
int result = 0;
for (int index = 0; index < word.length(); index++) {
if (word.charAt(index) == '1') {
result ^= index + 1;
}
}
return result;
}
static String flip(String word, int... positions) {
char[] bits = word.toCharArray();
for (int position : positions) {
bits[position - 1] = bits[position - 1] == '0' ? '1' : '0';
}
return new String(bits);
}
static String decode(String word) {
int position = syndrome(word);
String corrected = position == 0 ? word : flip(word, position);
return ""
+ corrected.charAt(2)
+ corrected.charAt(4)
+ corrected.charAt(5)
+ corrected.charAt(6);
}
public static void main(String[] args) {
String sent = encode("1011");
System.out.println("data 1011 is sent as " + sent + " with syndrome " + syndrome(sent));
for (int position = 1; position <= 7; position++) {
String received = flip(sent, position);
int result = syndrome(received);
String binary = "000" + Integer.toBinaryString(result);
System.out.println(
"bit "
+ position
+ " flipped: "
+ received
+ " syndrome "
+ result
+ " ("
+ binary.substring(binary.length() - 3)
+ ") decoded "
+ decode(received));
}
String two = flip(sent, 2, 6);
System.out.println(
"\nbits 2 and 6 flipped: "
+ two
+ " syndrome "
+ syndrome(two)
+ " decoded "
+ decode(two)
+ " (wrong: two errors look like one)");
}
} Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java
C++23 · main.cpp
#include <print>
#include <span>
#include <string>
#include <vector>
std::string encode(const std::string &data) {
const int first = data[0] - '0', second = data[1] - '0';
const int third = data[2] - '0', fourth = data[3] - '0';
const std::vector<int> bits = {first ^ second ^ fourth,
first ^ third ^ fourth,
first,
second ^ third ^ fourth,
second,
third,
fourth};
std::string word;
for (const int bit : bits) {
word += static_cast<char>('0' + bit);
}
return word;
}
int syndrome(const std::string &word) {
int result = 0;
for (std::size_t index = 0; index < word.size(); ++index) {
if (word[index] == '1') {
result ^= static_cast<int>(index + 1);
}
}
return result;
}
std::string flip(std::string word, std::span<const int> positions) {
for (const int position : positions) {
word[position - 1] = word[position - 1] == '0' ? '1' : '0';
}
return word;
}
std::string decode(std::string word) {
const int position = syndrome(word);
if (position != 0) {
const int positions[] = {position};
word = flip(word, positions);
}
return {word[2], word[4], word[5], word[6]};
}
int main() {
const auto sent = encode("1011");
std::println("data 1011 is sent as {} with syndrome {}", sent,
syndrome(sent));
for (int position = 1; position <= 7; ++position) {
const int positions[] = {position};
const auto received = flip(sent, positions);
const int result = syndrome(received);
std::println("bit {} flipped: {} syndrome {} ({:03b}) decoded {}",
position, received, result, result, decode(received));
}
const int positions[] = {2, 6};
const auto two = flip(sent, positions);
std::println("\nbits 2 and 6 flipped: {} syndrome {} decoded {} "
"(wrong: two errors look like one)",
two, syndrome(two), decode(two));
} Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main
C# 14 · .NET 10 · app.cs
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var sent = Encode("1011");
Console.WriteLine($"data 1011 is sent as {sent} with syndrome {Syndrome(sent)}");
for (int position = 1; position <= 7; position++)
{
var received = Flip(sent, [position]);
int result = Syndrome(received);
string binary = Convert.ToString(result, 2).PadLeft(3, '0');
Console.WriteLine($"bit {position} flipped: {received} syndrome {result} "
+ $"({binary}) decoded {Decode(received)}");
}
var two = Flip(sent, [2, 6]);
Console.WriteLine($"\nbits 2 and 6 flipped: {two} syndrome {Syndrome(two)} "
+ $"decoded {Decode(two)} (wrong: two errors look like one)");
static string Encode(string data)
{
int first = data[0] - '0', second = data[1] - '0';
int third = data[2] - '0', fourth = data[3] - '0';
int[] bits = [first ^ second ^ fourth, first ^ third ^ fourth, first,
second ^ third ^ fourth, second, third, fourth];
return string.Concat(bits);
}
static int Syndrome(string word)
{
int result = 0;
for (int index = 0; index < word.Length; index++)
{
if (word[index] == '1')
{
result ^= index + 1;
}
}
return result;
}
static string Flip(string word, int[] positions)
{
char[] bits = word.ToCharArray();
foreach (int position in positions)
{
bits[position - 1] = bits[position - 1] == '0' ? '1' : '0';
}
return new string(bits);
}
static string Decode(string word)
{
int position = Syndrome(word);
var corrected = position == 0 ? word : Flip(word, [position]);
return $"{corrected[2]}{corrected[4]}{corrected[5]}{corrected[6]}";
} Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs
C23 · main.c
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static void encode(const char *data, char word[8]) {
const uint8_t first = (uint8_t)(data[0] - '0');
const uint8_t second = (uint8_t)(data[1] - '0');
const uint8_t third = (uint8_t)(data[2] - '0');
const uint8_t fourth = (uint8_t)(data[3] - '0');
const uint8_t bits[] = {first ^ second ^ fourth,
first ^ third ^ fourth,
first,
second ^ third ^ fourth,
second,
third,
fourth};
for (size_t i = 0; i < 7; ++i) {
word[i] = (char)('0' + bits[i]);
}
word[7] = '\0';
}
static unsigned syndrome(const char *word) {
unsigned result = 0;
for (unsigned i = 0; i < 7; ++i) {
if (word[i] == '1') {
result ^= i + 1;
}
}
return result;
}
static void flip(char *word, unsigned position) {
word[position - 1] = word[position - 1] == '0' ? '1' : '0';
}
static void decode(const char *word, char data[5]) {
char corrected[8];
memcpy(corrected, word, 8);
const unsigned position = syndrome(word);
if (position != 0) {
flip(corrected, position);
}
const unsigned positions[] = {2, 4, 5, 6};
for (size_t i = 0; i < 4; ++i) {
data[i] = corrected[positions[i]];
}
data[4] = '\0';
}
int main(void) {
char sent[8], received[8], data[5];
encode("1011", sent);
printf("data 1011 is sent as %s with syndrome %u\n", sent, syndrome(sent));
for (unsigned position = 1; position <= 7; ++position) {
memcpy(received, sent, 8);
flip(received, position);
const unsigned result = syndrome(received);
decode(received, data);
printf("bit %u flipped: %s syndrome %u (%u%u%u) decoded %s\n", position,
received, result, (result >> 2) & 1, (result >> 1) & 1, result & 1,
data);
}
memcpy(received, sent, 8);
flip(received, 2);
flip(received, 6);
decode(received, data);
printf("\nbits 2 and 6 flipped: %s syndrome %u decoded %s "
"(wrong: two errors look like one)\n",
received, syndrome(received), data);
return 0;
} Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main
PHP 8.5 · main.php
<?php
declare(strict_types=1);
function encode(string $data): string
{
[$first, $second, $third, $fourth] = array_map('intval', str_split($data));
return implode('', [
$first ^ $second ^ $fourth,
$first ^ $third ^ $fourth,
$first,
$second ^ $third ^ $fourth,
$second,
$third,
$fourth,
]);
}
function syndrome(string $word): int
{
$result = 0;
for ($index = 0; $index < strlen($word); ++$index) {
if ($word[$index] === '1') {
$result ^= $index + 1;
}
}
return $result;
}
/** @param list<int> $positions */
function flip(string $word, array $positions): string
{
foreach ($positions as $position) {
$word[$position - 1] = $word[$position - 1] === '0' ? '1' : '0';
}
return $word;
}
function decode(string $word): string
{
$position = syndrome($word);
$corrected = $position === 0 ? $word : flip($word, [$position]);
return $corrected[2] . $corrected[4] . $corrected[5] . $corrected[6];
}
$sent = encode('1011');
echo "data 1011 is sent as {$sent} with syndrome ", syndrome($sent), "\n";
for ($position = 1; $position <= 7; ++$position) {
$received = flip($sent, [$position]);
$result = syndrome($received);
$binary = str_pad(decbin($result), 3, '0', STR_PAD_LEFT);
echo "bit {$position} flipped: {$received} syndrome {$result} ",
"({$binary}) decoded ", decode($received), "\n";
}
$two = flip($sent, [2, 6]);
echo "\nbits 2 and 6 flipped: {$two} syndrome ", syndrome($two),
' decoded ', decode($two), " (wrong: two errors look like one)\n"; Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php
Rust 1.99 · main.rs
fn encode(data: &str) -> String {
let bits: Vec<u8> = data.bytes().map(|bit| bit - b'0').collect();
let (first, second, third, fourth) = (bits[0], bits[1], bits[2], bits[3]);
[
first ^ second ^ fourth,
first ^ third ^ fourth,
first,
second ^ third ^ fourth,
second,
third,
fourth,
]
.iter()
.map(|bit| char::from(b'0' + bit))
.collect()
}
fn syndrome(word: &str) -> usize {
word.bytes().enumerate().fold(0, |result, (index, bit)| {
if bit == b'1' {
result ^ (index + 1)
} else {
result
}
})
}
fn flip(word: &str, positions: &[usize]) -> String {
let mut bits: Vec<char> = word.chars().collect();
for &position in positions {
bits[position - 1] = if bits[position - 1] == '0' { '1' } else { '0' };
}
bits.into_iter().collect()
}
fn decode(word: &str) -> String {
let position = syndrome(word);
let corrected = if position == 0 {
word.to_owned()
} else {
flip(word, &[position])
};
corrected
.chars()
.enumerate()
.filter_map(|(index, bit)| [2, 4, 5, 6].contains(&index).then_some(bit))
.collect()
}
fn main() {
let sent = encode("1011");
println!(
"data 1011 is sent as {sent} with syndrome {}",
syndrome(&sent)
);
for position in 1..=7 {
let received = flip(&sent, &[position]);
let result = syndrome(&received);
println!(
"bit {position} flipped: {received} syndrome {result} ({result:03b}) decoded {}",
decode(&received)
);
}
let two = flip(&sent, &[2, 6]);
println!(
"\nbits 2 and 6 flipped: {two} syndrome {} decoded {} (wrong: two errors look like one)",
syndrome(&two),
decode(&two)
);
} Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main
TypeScript 6.0 · main.ts
function encode(data: string): string {
const bits = [...data].map(Number);
const first = bits[0] ?? 0;
const second = bits[1] ?? 0;
const third = bits[2] ?? 0;
const fourth = bits[3] ?? 0;
return [
first ^ second ^ fourth,
first ^ third ^ fourth,
first,
second ^ third ^ fourth,
second,
third,
fourth,
].join("");
}
function syndrome(word: string): number {
let result = 0;
for (let index = 0; index < word.length; index++) {
if (word[index] === "1") result ^= index + 1;
}
return result;
}
function flip(word: string, positions: readonly number[]): string {
const bits = [...word];
for (const position of positions) {
bits[position - 1] = bits[position - 1] === "0" ? "1" : "0";
}
return bits.join("");
}
function decode(word: string): string {
const position = syndrome(word);
const corrected = position ? flip(word, [position]) : word;
return [2, 4, 5, 6].map((index) => corrected[index]).join("");
}
const sent = encode("1011");
console.log(`data 1011 is sent as ${sent} with syndrome ${syndrome(sent)}`);
for (let position = 1; position <= 7; position++) {
const received = flip(sent, [position]);
const result = syndrome(received);
console.log(
`bit ${position} flipped: ${received} syndrome ${result} ` +
`(${result.toString(2).padStart(3, "0")}) decoded ${decode(received)}`,
);
}
const two = flip(sent, [2, 6]);
console.log(
`\nbits 2 and 6 flipped: ${two} syndrome ${syndrome(two)} ` +
`decoded ${decode(two)} (wrong: two errors look like one)`,
); Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts
Go 1.27 · main.go
package main
import "fmt"
func encode(data string) string {
first, second := data[0]-'0', data[1]-'0'
third, fourth := data[2]-'0', data[3]-'0'
bits := []byte{first ^ second ^ fourth, first ^ third ^ fourth,
first, second ^ third ^ fourth, second, third, fourth}
for i := range bits {
bits[i] += '0'
}
return string(bits)
}
func syndrome(word string) int {
result := 0
for index, bit := range word {
if bit == '1' {
result ^= index + 1
}
}
return result
}
func flip(word string, positions ...int) string {
bits := []byte(word)
for _, position := range positions {
bits[position-1] ^= 1
}
return string(bits)
}
func decode(word string) string {
position := syndrome(word)
if position != 0 {
word = flip(word, position)
}
return string([]byte{word[2], word[4], word[5], word[6]})
}
func main() {
sent := encode("1011")
fmt.Printf("data 1011 is sent as %s with syndrome %d\n", sent, syndrome(sent))
for position := 1; position <= 7; position++ {
received := flip(sent, position)
result := syndrome(received)
fmt.Printf("bit %d flipped: %s syndrome %d (%03b) decoded %s\n",
position, received, result, result, decode(received))
}
two := flip(sent, 2, 6)
fmt.Printf("\nbits 2 and 6 flipped: %s syndrome %d decoded %s "+
"(wrong: two errors look like one)\n", two, syndrome(two), decode(two))
} Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go
Swift 6.4 · main.swift
func encode(_ data: String) -> String {
let bits = data.map { $0 == "1" ? 1 : 0 }
let (first, second, third, fourth) = (bits[0], bits[1], bits[2], bits[3])
return [
first ^ second ^ fourth, first ^ third ^ fourth, first,
second ^ third ^ fourth, second, third, fourth,
].map { String($0) }.joined()
}
func syndrome(_ word: String) -> Int {
word.enumerated().reduce(0) { result, item in
item.element == "1" ? result ^ (item.offset + 1) : result
}
}
func flip(_ word: String, at positions: [Int]) -> String {
var bits = Array(word)
for position in positions {
bits[position - 1] = bits[position - 1] == "0" ? "1" : "0"
}
return String(bits)
}
func decode(_ word: String) -> String {
let position = syndrome(word)
let corrected = Array(position == 0 ? word : flip(word, at: [position]))
return String([corrected[2], corrected[4], corrected[5], corrected[6]])
}
let sent = encode("1011")
print("data 1011 is sent as \(sent) with syndrome \(syndrome(sent))")
for position in 1...7 {
let received = flip(sent, at: [position])
let result = syndrome(received)
let digits = String(result, radix: 2)
let binary = String(repeating: "0", count: 3 - digits.count) + digits
print(
"bit \(position) flipped: \(received) syndrome \(result) "
+ "(\(binary)) decoded \(decode(received))")
}
let two = flip(sent, at: [2, 6])
print(
"\nbits 2 and 6 flipped: \(two) syndrome \(syndrome(two)) "
+ "decoded \(decode(two)) (wrong: two errors look like one)") Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main
Ruby 4.0 · main.rb
# frozen_string_literal: true
def encode(data)
first, second, third, fourth = data.chars.map(&:to_i)
[
first ^ second ^ fourth, first ^ third ^ fourth, first,
second ^ third ^ fourth, second, third, fourth
].join
end
def syndrome(word)
word.chars.each_with_index.reduce(0) do |result, (bit, index)|
bit == '1' ? result ^ (index + 1) : result
end
end
def flip(word, positions)
bits = word.chars
positions.each { |position| bits[position - 1] = bits[position - 1] == '0' ? '1' : '0' }
bits.join
end
def decode(word)
position = syndrome(word)
corrected = position.zero? ? word : flip(word, [position])
[2, 4, 5, 6].map { |index| corrected[index] }.join
end
sent = encode('1011')
puts "data 1011 is sent as #{sent} with syndrome #{syndrome(sent)}"
(1..7).each do |position|
received = flip(sent, [position])
result = syndrome(received)
puts "bit #{position} flipped: #{received} syndrome #{result} " \
"(#{result.to_s(2).rjust(3, '0')}) decoded #{decode(received)}"
end
two = flip(sent, [2, 6])
puts "\nbits 2 and 6 flipped: #{two} syndrome #{syndrome(two)} " \
"decoded #{decode(two)} (wrong: two errors look like one)" Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb
Kotlin 2.4 · Main.kt
fun encode(data: String): String {
val bits = data.map { it.digitToInt() }
val (first, second, third, fourth) = bits
return listOf(
first xor second xor fourth,
first xor third xor fourth,
first,
second xor third xor fourth,
second,
third,
fourth,
).joinToString("")
}
fun syndrome(word: String): Int =
word.withIndex().fold(0) { result, (index, bit) ->
if (bit == '1') result xor (index + 1) else result
}
fun flip(
word: String,
positions: List<Int>,
): String {
val bits = word.toCharArray()
for (position in positions) {
bits[position - 1] = if (bits[position - 1] == '0') '1' else '0'
}
return bits.concatToString()
}
fun decode(word: String): String {
val position = syndrome(word)
val corrected = if (position == 0) word else flip(word, listOf(position))
return listOf(2, 4, 5, 6).map { corrected[it] }.joinToString("")
}
fun main() {
val sent = encode("1011")
println("data 1011 is sent as $sent with syndrome ${syndrome(sent)}")
for (position in 1..7) {
val received = flip(sent, listOf(position))
val result = syndrome(received)
val binary = result.toString(2).padStart(3, '0')
println(
"bit $position flipped: $received syndrome $result " +
"($binary) decoded ${decode(received)}",
)
}
val two = flip(sent, listOf(2, 6))
println(
"\nbits 2 and 6 flipped: $two syndrome ${syndrome(two)} " +
"decoded ${decode(two)} (wrong: two errors look like one)",
)
} Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar
Dart 3.13 · main.dart
String encode(String data) {
final bits = data.split('').map(int.parse).toList();
final first = bits[0], second = bits[1], third = bits[2], fourth = bits[3];
return [
first ^ second ^ fourth,
first ^ third ^ fourth,
first,
second ^ third ^ fourth,
second,
third,
fourth,
].join();
}
int syndrome(String word) {
var result = 0;
for (var index = 0; index < word.length; index++) {
if (word[index] == '1') result ^= index + 1;
}
return result;
}
String flip(String word, List<int> positions) {
final bits = word.split('');
for (final position in positions) {
bits[position - 1] = bits[position - 1] == '0' ? '1' : '0';
}
return bits.join();
}
String decode(String word) {
final position = syndrome(word);
final corrected = position == 0 ? word : flip(word, [position]);
return [2, 4, 5, 6].map((index) => corrected[index]).join();
}
void main() {
final sent = encode('1011');
print('data 1011 is sent as $sent with syndrome ${syndrome(sent)}');
for (var position = 1; position <= 7; position++) {
final received = flip(sent, [position]);
final result = syndrome(received);
final binary = result.toRadixString(2).padLeft(3, '0');
print(
'bit $position flipped: $received syndrome $result '
'($binary) decoded ${decode(received)}',
);
}
final two = flip(sent, [2, 6]);
print(
'\nbits 2 and 6 flipped: $two syndrome ${syndrome(two)} '
'decoded ${decode(two)} (wrong: two errors look like one)',
);
} Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart
What every language printed
data 1011 is sent as 0110011 with syndrome 0 bit 1 flipped: 1110011 syndrome 1 (001) decoded 1011 bit 2 flipped: 0010011 syndrome 2 (010) decoded 1011 bit 3 flipped: 0100011 syndrome 3 (011) decoded 1011 bit 4 flipped: 0111011 syndrome 4 (100) decoded 1011 bit 5 flipped: 0110111 syndrome 5 (101) decoded 1011 bit 6 flipped: 0110001 syndrome 6 (110) decoded 1011 bit 7 flipped: 0110010 syndrome 7 (111) decoded 1011 bits 2 and 6 flipped: 0010001 syndrome 4 decoded 1001 (wrong: two errors look like one)
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. Runs on this device: a JavaScript build of this program (about 10 KB), made when the page was built. The first run also downloads the JavaScript runner (about 0.6 MB), which is kept for the next runs. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 152 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a .NET build of this program (about 3 KB), made when the page was built. The first run also downloads .NET (about 3.6 MB), which is kept for the next runs. Edit runs your changes in the browser: the first edited run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 8 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads PHP (about 4.3 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 21 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads the JavaScript runner (about 0.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 717 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 1.7 MB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads Ruby (about 10.2 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 183 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 16 KB), made when the page was built. To change the code, copy it and run it with the command below.Your run, in this browser
Every single flip produced its own position as the syndrome, and every one was corrected back to the data 1011. The last line is the warning from the previous section: flipping bits 2 and 6 gives the syndrome 2 XOR 6 = 4, so the decoder flips a third bit and returns 1001, wrong and without complaint.
The construction grows: r check bits can point at any of positions, so they protect up to data bits, which gives Hamming(15,11) and Hamming(31,26). Adding one more parity bit over the whole word raises the minimum distance to 4, which lets a receiver correct any single error and still detect any double one.
Trace all seven single flips, then preserve the original 2-and 6 counterexample that decodes to 1001.
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- The original Hamming(7,4) code stores checks at positions 1,2 and 4 and data at 3,5,6 and 7.
- The original seven one-bit cases produce syndromes 1 through 7 and recover 1011.
- The original pair gives syndrome 4; the single-error decoder flips another bit and returns 1001, demonstrating the model limit.
Checkpoint
Check: A Hamming syndrome locates a single-bit error
End-around carry forms the Internet checksum
IPv4, UDP and TCP do not use parity: they use the Internet checksum of RFC 1071, which treats the data as 16-bit numbers and adds them up in ones’ complement arithmetic:
- Pair the bytes into 16-bit words, most significant byte first; an odd number of bytes gets one zero byte at the end.
- Add the words. Whenever a sum overflows 16 bits, add the carry back in at the bottom (the end-around carry: Adding a carry beyond the word width back into the low-order bits, as required by the Internet checksum's ones' complement arithmetic.).
- The checksum is the complement of the sum: every bit flipped.
For the IPv4 header, the checksum field is set to zero while the sender computes it (RFC 791). The receiver adds up every word of the header including the checksum, and a header that arrived intact sums to 0xFFFF.
"""The 16-bit Internet checksum (RFC 1071) of an IPv4 header, checked, then updated after a router lowers the TTL."""
# A 20-byte IPv4 header with the checksum field (bytes 10 and 11) set to zero. Addresses from the
# documentation ranges of RFC 5737: 192.0.2.10 to 198.51.100.20, TTL 64, protocol 6 (TCP).
header = bytearray.fromhex("4500 003c 1c46 4000 4006 0000 c000 020a c633 6414")
def add(*words):
"""Ones' complement addition: a carry out of the top bit is added back at the bottom (end-around carry)."""
total = 0
for w in words:
total += w
total = (total & 0xFFFF) + (total >> 16)
return total
def words_of(data):
"""The data as 16-bit words; an odd length is padded with one zero byte."""
if len(data) % 2:
data = bytes(data) + b"\x00"
return [data[i] << 8 | data[i + 1] for i in range(0, len(data), 2)]
def internet_checksum(data):
"""The complement of the ones' complement sum of the data's 16-bit words."""
return ~add(*words_of(data)) & 0xFFFF
print("words: ", " ".join(f"{w:04x}" for w in words_of(header)))
print(f"sum: {add(*words_of(header)):04x}")
checksum = internet_checksum(header)
print(f"checksum: {checksum:04x}")
header[10:12] = checksum.to_bytes(2, "big")
print(f"receiver: the sum of all ten words, checksum included, is {add(*words_of(header)):04x}")
# A router forwards the packet: TTL 64 becomes 63, so the word 4006 becomes 3f06.
old_word = header[8] << 8 | header[9]
header[8] -= 1
new_word = header[8] << 8 | header[9]
hc = header[10] << 8 | header[11]
incremental = ~add(~hc & 0xFFFF, ~old_word & 0xFFFF, new_word) & 0xFFFF # RFC 1624, equation 3
header[10:12] = b"\x00\x00"
print()
print(f"after the TTL change: incremental {incremental:04x}, recomputed {internet_checksum(header):04x}")
# RFC 1624's own example: the other fields sum to CD7A and one field changes from 5555 to 3285.
c, m, m_new = 0xCD7A, 0x5555, 0x3285
hc = ~add(c, m) & 0xFFFF
print()
print(f"old checksum {hc:04x}, recomputed after the change {~add(c, m_new) & 0xFFFF:04x}")
print(f"RFC 1141 shortcut, HC + m + ~m': {add(hc, m, ~m_new & 0xFFFF):04x}")
print(f"RFC 1624 equation 3, ~(~HC + ~m + m'): {~add(~hc & 0xFFFF, ~m & 0xFFFF, m_new) & 0xFFFF:04x}") Output
words: 4500 003c 1c46 4000 4006 0000 c000 020a c633 6414 sum: cddb checksum: 3224 receiver: the sum of all ten words, checksum included, is ffff after the TTL change: incremental 3324, recomputed 3324 old checksum dd2f, recomputed after the change 0000 RFC 1141 shortcut, HC + m + ~m': ffff RFC 1624 equation 3, ~(~HC + ~m + m'): 0000
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 internet_checksum.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Python 3.14 · main.py
def add(words: list[int]) -> int:
total = 0
for word in words:
total += word
total = (total & 0xFFFF) + (total >> 16)
return total
def words_of(data: bytes | bytearray) -> list[int]:
padded = bytes(data) + (b"\0" if len(data) % 2 else b"")
return [
padded[index] << 8 | padded[index + 1] for index in range(0, len(padded), 2)
]
def checksum(data: bytes | bytearray) -> int:
return ~add(words_of(data)) & 0xFFFF
header = bytearray.fromhex("4500 003c 1c46 4000 4006 0000 c000 020a c633 6414")
print("words: ", " ".join(f"{word:04x}" for word in words_of(header)))
print(f"sum: {add(words_of(header)):04x}")
value = checksum(header)
print(f"checksum: {value:04x}")
header[10:12] = value.to_bytes(2, "big")
print(
f"receiver: the sum of all ten words, checksum included, is {add(words_of(header)):04x}"
)
old_word = header[8] << 8 | header[9]
header[8] -= 1
new_word = header[8] << 8 | header[9]
incremental = ~add([~value & 0xFFFF, ~old_word & 0xFFFF, new_word]) & 0xFFFF
header[10:12] = b"\0\0"
print(
f"\nafter the TTL change: incremental {incremental:04x}, recomputed {checksum(header):04x}"
)
other, old, updated = 0xCD7A, 0x5555, 0x3285
value = ~add([other, old]) & 0xFFFF
recomputed = ~add([other, updated]) & 0xFFFF
print(f"\nold checksum {value:04x}, recomputed after the change {recomputed:04x}")
print(f"RFC 1141 shortcut, HC + m + ~m': {add([value, old, ~updated & 0xFFFF]):04x}")
fixed = ~add([~value & 0xFFFF, ~old & 0xFFFF, updated]) & 0xFFFF
print(f"RFC 1624 equation 3, ~(~HC + ~m + m'): {fixed:04x}") Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py
JavaScript Node 24 · main.mjs
function add(words) {
let total = 0;
for (const word of words) {
total += word;
total = (total & 0xffff) + (total >>> 16);
}
return total;
}
const hex = (word) => word.toString(16).padStart(4, "0");
const words = [0x4500, 0x003c, 0x1c46, 0x4000, 0x4006, 0x0000, 0xc000, 0x020a, 0xc633, 0x6414];
console.log("words: " + words.map(hex).join(" "));
console.log("sum: " + hex(add(words)));
let value = ~add(words) & 0xffff;
console.log("checksum: " + hex(value));
words[5] = value;
console.log("receiver: the sum of all ten words, checksum included, is " + hex(add(words)));
const oldWord = words[4];
words[4] -= 0x0100;
const newWord = words[4];
const incremental = ~add([~value & 0xffff, ~oldWord & 0xffff, newWord]) & 0xffff;
words[5] = 0;
console.log(
`\nafter the TTL change: incremental ${hex(incremental)}, ` +
`recomputed ${hex(~add(words) & 0xffff)}`,
);
const other = 0xcd7a;
const old = 0x5555;
const updated = 0x3285;
value = ~add([other, old]) & 0xffff;
console.log(
`\nold checksum ${hex(value)}, recomputed after the change ` +
hex(~add([other, updated]) & 0xffff),
);
const shortcut = add([value, old, ~updated & 0xffff]);
console.log("RFC 1141 shortcut, HC + m + ~m': " + hex(shortcut));
const fixed = ~add([~value & 0xffff, ~old & 0xffff, updated]) & 0xffff;
console.log("RFC 1624 equation 3, ~(~HC + ~m + m'): " + hex(fixed)); Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs
Java 25 LTS · Main.java
import java.util.Locale;
public class Main {
static int add(int... words) {
int total = 0;
for (int word : words) {
total += word;
total = (total & 0xffff) + (total >>> 16);
}
return total;
}
static String hex(int word) {
return String.format("%04x", word);
}
public static void main(String[] args) {
Locale.setDefault(Locale.ROOT);
int[] words = {0x4500, 0x003c, 0x1c46, 0x4000, 0x4006, 0x0000, 0xc000, 0x020a, 0xc633, 0x6414};
var shown = new StringBuilder();
for (int word : words) {
if (shown.length() != 0) {
shown.append(' ');
}
shown.append(hex(word));
}
System.out.println("words: " + shown);
System.out.println("sum: " + hex(add(words)));
int value = ~add(words) & 0xffff;
System.out.println("checksum: " + hex(value));
words[5] = value;
System.out.println(
"receiver: the sum of all ten words, checksum included, is " + hex(add(words)));
int oldWord = words[4];
words[4] -= 0x0100;
int newWord = words[4];
int incremental = ~add(~value & 0xffff, ~oldWord & 0xffff, newWord) & 0xffff;
words[5] = 0;
System.out.println(
"\nafter the TTL change: incremental "
+ hex(incremental)
+ ", recomputed "
+ hex(~add(words) & 0xffff));
int other = 0xcd7a, old = 0x5555, updated = 0x3285;
value = ~add(other, old) & 0xffff;
System.out.println(
"\nold checksum "
+ hex(value)
+ ", recomputed after the change "
+ hex(~add(other, updated) & 0xffff));
System.out.println(
"RFC 1141 shortcut, HC + m + ~m': " + hex(add(value, old, ~updated & 0xffff)));
int fixed = ~add(~value & 0xffff, ~old & 0xffff, updated) & 0xffff;
System.out.println("RFC 1624 equation 3, ~(~HC + ~m + m'): " + hex(fixed));
}
} Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java
C++23 · main.cpp
#include <format>
#include <initializer_list>
#include <print>
#include <span>
#include <string>
#include <vector>
unsigned add(std::span<const unsigned> words) {
unsigned total = 0;
for (const auto word : words) {
total += word;
total = (total & 0xffff) + (total >> 16);
}
return total;
}
unsigned sum(std::initializer_list<unsigned> words) {
return add(std::span(words.begin(), words.size()));
}
int main() {
std::vector<unsigned> words = {0x4500, 0x003c, 0x1c46, 0x4000, 0x4006,
0x0000, 0xc000, 0x020a, 0xc633, 0x6414};
std::string shown;
for (const auto word : words) {
shown += (shown.empty() ? "" : " ") + std::format("{:04x}", word);
}
std::println("words: {}", shown);
std::println("sum: {:04x}", add(words));
auto value = ~add(words) & 0xffff;
std::println("checksum: {:04x}", value);
words[5] = value;
std::println(
"receiver: the sum of all ten words, checksum included, is {:04x}",
add(words));
const auto old_word = words[4];
words[4] -= 0x0100;
const auto new_word = words[4];
const auto incremental =
~sum({~value & 0xffff, ~old_word & 0xffff, new_word}) & 0xffff;
words[5] = 0;
std::println("\nafter the TTL change: incremental {:04x}, recomputed {:04x}",
incremental, ~add(words) & 0xffff);
const unsigned other = 0xcd7a, old = 0x5555, updated = 0x3285;
value = ~sum({other, old}) & 0xffff;
std::println("\nold checksum {:04x}, recomputed after the change {:04x}",
value, ~sum({other, updated}) & 0xffff);
std::println("RFC 1141 shortcut, HC + m + ~m': {:04x}",
sum({value, old, ~updated & 0xffff}));
const auto fixed = ~sum({~value & 0xffff, ~old & 0xffff, updated}) & 0xffff;
std::println("RFC 1624 equation 3, ~(~HC + ~m + m'): {:04x}", fixed);
} Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main
C# 14 · .NET 10 · app.cs
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
int[] words = [0x4500, 0x003c, 0x1c46, 0x4000, 0x4006,
0x0000, 0xc000, 0x020a, 0xc633, 0x6414];
Console.WriteLine("words: " + string.Join(" ", words.Select(Hex)));
Console.WriteLine("sum: " + Hex(Add(words)));
int value = ~Add(words) & 0xffff;
Console.WriteLine("checksum: " + Hex(value));
words[5] = value;
Console.WriteLine("receiver: the sum of all ten words, checksum included, is "
+ Hex(Add(words)));
int oldWord = words[4];
words[4] -= 0x0100;
int newWord = words[4];
int incremental = ~Add([~value & 0xffff, ~oldWord & 0xffff, newWord]) & 0xffff;
words[5] = 0;
Console.WriteLine($"\nafter the TTL change: incremental {Hex(incremental)}, "
+ $"recomputed {Hex(~Add(words) & 0xffff)}");
int other = 0xcd7a, old = 0x5555, updated = 0x3285;
value = ~Add([other, old]) & 0xffff;
Console.WriteLine($"\nold checksum {Hex(value)}, recomputed after the change "
+ Hex(~Add([other, updated]) & 0xffff));
Console.WriteLine("RFC 1141 shortcut, HC + m + ~m': "
+ Hex(Add([value, old, ~updated & 0xffff])));
int fixedValue = ~Add([~value & 0xffff, ~old & 0xffff, updated]) & 0xffff;
Console.WriteLine("RFC 1624 equation 3, ~(~HC + ~m + m'): " + Hex(fixedValue));
static int Add(int[] words)
{
int total = 0;
foreach (int word in words)
{
total += word;
total = (total & 0xffff) + (total >> 16);
}
return total;
}
static string Hex(int word) => word.ToString("x4", CultureInfo.InvariantCulture); Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs
C23 · main.c
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
static uint32_t add(const uint32_t *words, size_t count) {
uint32_t total = 0;
for (size_t i = 0; i < count; ++i) {
total += words[i];
total = (total & 0xffff) + (total >> 16);
}
return total;
}
int main(void) {
uint32_t words[] = {0x4500, 0x003c, 0x1c46, 0x4000, 0x4006,
0x0000, 0xc000, 0x020a, 0xc633, 0x6414};
fputs("words: ", stdout);
for (size_t i = 0; i < 10; ++i) {
printf("%s%04x", i == 0 ? "" : " ", words[i]);
}
printf("\nsum: %04x\n", add(words, 10));
uint32_t value = ~add(words, 10) & 0xffff;
printf("checksum: %04x\n", value);
words[5] = value;
printf("receiver: the sum of all ten words, checksum included, is %04x\n",
add(words, 10));
const uint32_t old_word = words[4];
words[4] -= 0x0100;
const uint32_t new_word = words[4];
const uint32_t update_words[] = {~value & 0xffff, ~old_word & 0xffff,
new_word};
const uint32_t incremental = ~add(update_words, 3) & 0xffff;
words[5] = 0;
printf("\nafter the TTL change: incremental %04x, recomputed %04x\n",
incremental, ~add(words, 10) & 0xffff);
const uint32_t other = 0xcd7a, old = 0x5555, updated = 0x3285;
const uint32_t prior_words[] = {other, old}, new_words[] = {other, updated};
value = ~add(prior_words, 2) & 0xffff;
printf("\nold checksum %04x, recomputed after the change %04x\n", value,
~add(new_words, 2) & 0xffff);
const uint32_t shortcut[] = {value, old, ~updated & 0xffff};
printf("RFC 1141 shortcut, HC + m + ~m': %04x\n", add(shortcut, 3));
const uint32_t fixed_words[] = {~value & 0xffff, ~old & 0xffff, updated};
printf("RFC 1624 equation 3, ~(~HC + ~m + m'): %04x\n",
~add(fixed_words, 3) & 0xffff);
return 0;
} Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main
PHP 8.5 · main.php
<?php
declare(strict_types=1);
/** @param list<int> $words */
function add(array $words): int
{
$total = 0;
foreach ($words as $word) {
$total += $word;
$total = ($total & 0xffff) + ($total >> 16);
}
return $total;
}
/** @param list<int> $data @return list<int> */
function wordsOf(array $data): array
{
$words = [];
for ($index = 0; $index < count($data); $index += 2) {
$words[] = $data[$index] << 8 | ($data[$index + 1] ?? 0);
}
return $words;
}
/** @param list<int> $data */
function checksum(array $data): int
{
return ~add(wordsOf($data)) & 0xffff;
}
function hexWord(int $word): string
{
return sprintf('%04x', $word);
}
$header = array_map('hexdec', str_split('4500003c1c46400040060000c000020ac6336414', 2));
echo 'words: ', implode(' ', array_map('hexWord', wordsOf($header))), "\n";
echo 'sum: ', hexWord(add(wordsOf($header))), "\n";
$value = checksum($header);
echo 'checksum: ', hexWord($value), "\n";
$header[10] = $value >> 8;
$header[11] = $value & 255;
echo 'receiver: the sum of all ten words, checksum included, is ',
hexWord(add(wordsOf($header))), "\n";
$oldWord = $header[8] << 8 | $header[9];
--$header[8];
$newWord = $header[8] << 8 | $header[9];
$incremental = ~add([~$value & 0xffff, ~$oldWord & 0xffff, $newWord]) & 0xffff;
$header[10] = $header[11] = 0;
echo "\nafter the TTL change: incremental ", hexWord($incremental),
', recomputed ', hexWord(checksum($header)), "\n";
[$other, $old, $updated] = [0xcd7a, 0x5555, 0x3285];
$value = ~add([$other, $old]) & 0xffff;
echo "\nold checksum ", hexWord($value), ', recomputed after the change ',
hexWord(~add([$other, $updated]) & 0xffff), "\n";
echo "RFC 1141 shortcut, HC + m + ~m': ", hexWord(add([$value, $old, ~$updated & 0xffff])), "\n";
$fixed = ~add([~$value & 0xffff, ~$old & 0xffff, $updated]) & 0xffff;
echo "RFC 1624 equation 3, ~(~HC + ~m + m'): ", hexWord($fixed), "\n"; Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php
Rust 1.99 · main.rs
fn add(words: &[u32]) -> u32 {
words.iter().fold(0, |total, word| {
let next = total + word;
(next & 0xffff) + (next >> 16)
})
}
fn words_of(data: &[u8]) -> Vec<u32> {
data.chunks(2)
.map(|pair| u32::from(pair[0]) << 8 | u32::from(*pair.get(1).unwrap_or(&0)))
.collect()
}
fn checksum(data: &[u8]) -> u32 {
!add(&words_of(data)) & 0xffff
}
fn main() {
let mut header = vec![
0x45, 0x00, 0x00, 0x3c, 0x1c, 0x46, 0x40, 0x00, 0x40, 0x06, 0x00, 0x00, 0xc0, 0x00, 0x02,
0x0a, 0xc6, 0x33, 0x64, 0x14,
];
let shown = words_of(&header)
.iter()
.map(|word| format!("{word:04x}"))
.collect::<Vec<_>>()
.join(" ");
println!("words: {shown}");
println!("sum: {:04x}", add(&words_of(&header)));
let mut value = checksum(&header);
println!("checksum: {value:04x}");
header[10] = (value >> 8) as u8;
header[11] = (value & 255) as u8;
println!(
"receiver: the sum of all ten words, checksum included, is {:04x}",
add(&words_of(&header))
);
let old_word = u32::from(header[8]) << 8 | u32::from(header[9]);
header[8] -= 1;
let new_word = u32::from(header[8]) << 8 | u32::from(header[9]);
let incremental = !add(&[!value & 0xffff, !old_word & 0xffff, new_word]) & 0xffff;
header[10] = 0;
header[11] = 0;
println!(
"\nafter the TTL change: incremental {incremental:04x}, recomputed {:04x}",
checksum(&header)
);
let (other, old, updated) = (0xcd7a, 0x5555, 0x3285);
value = !add(&[other, old]) & 0xffff;
println!(
"\nold checksum {value:04x}, recomputed after the change {:04x}",
!add(&[other, updated]) & 0xffff
);
println!(
"RFC 1141 shortcut, HC + m + ~m': {:04x}",
add(&[value, old, !updated & 0xffff])
);
let fixed = !add(&[!value & 0xffff, !old & 0xffff, updated]) & 0xffff;
println!("RFC 1624 equation 3, ~(~HC + ~m + m'): {fixed:04x}");
} Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main
TypeScript 6.0 · main.ts
function add(words: readonly number[]): number {
let total = 0;
for (const word of words) {
total += word;
total = (total & 0xffff) + (total >>> 16);
}
return total;
}
const hex = (word: number): string => word.toString(16).padStart(4, "0");
const words = [0x4500, 0x003c, 0x1c46, 0x4000, 0x4006, 0x0000, 0xc000, 0x020a, 0xc633, 0x6414];
console.log("words: " + words.map(hex).join(" "));
console.log("sum: " + hex(add(words)));
let value = ~add(words) & 0xffff;
console.log("checksum: " + hex(value));
words[5] = value;
console.log("receiver: the sum of all ten words, checksum included, is " + hex(add(words)));
const oldWord = words[4] ?? 0;
words[4] = oldWord - 0x0100;
const newWord = words[4];
const incremental = ~add([~value & 0xffff, ~oldWord & 0xffff, newWord]) & 0xffff;
words[5] = 0;
console.log(
`\nafter the TTL change: incremental ${hex(incremental)}, ` +
`recomputed ${hex(~add(words) & 0xffff)}`,
);
const other = 0xcd7a;
const old = 0x5555;
const updated = 0x3285;
value = ~add([other, old]) & 0xffff;
console.log(
`\nold checksum ${hex(value)}, recomputed after the change ` +
hex(~add([other, updated]) & 0xffff),
);
const shortcut = add([value, old, ~updated & 0xffff]);
console.log("RFC 1141 shortcut, HC + m + ~m': " + hex(shortcut));
const fixed = ~add([~value & 0xffff, ~old & 0xffff, updated]) & 0xffff;
console.log("RFC 1624 equation 3, ~(~HC + ~m + m'): " + hex(fixed)); Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts
Go 1.27 · main.go
package main
import (
"fmt"
"strings"
)
func add(words ...uint32) uint32 {
total := uint32(0)
for _, word := range words {
total += word
total = (total & 0xffff) + (total >> 16)
}
return total
}
func wordsOf(data []byte) []uint32 {
words := []uint32{}
for index := 0; index < len(data); index += 2 {
word := uint32(data[index]) << 8
if index+1 < len(data) {
word |= uint32(data[index+1])
}
words = append(words, word)
}
return words
}
func checksum(data []byte) uint32 { return ^add(wordsOf(data)...) & 0xffff }
func main() {
header := []byte{0x45, 0x00, 0x00, 0x3c, 0x1c, 0x46, 0x40, 0x00, 0x40, 0x06,
0x00, 0x00, 0xc0, 0x00, 0x02, 0x0a, 0xc6, 0x33, 0x64, 0x14}
shown := []string{}
for _, word := range wordsOf(header) {
shown = append(shown, fmt.Sprintf("%04x", word))
}
fmt.Println("words: ", strings.Join(shown, " "))
fmt.Printf("sum: %04x\n", add(wordsOf(header)...))
value := checksum(header)
fmt.Printf("checksum: %04x\n", value)
header[10], header[11] = byte(value>>8), byte(value&255)
fmt.Printf("receiver: the sum of all ten words, checksum included, is %04x\n",
add(wordsOf(header)...))
oldWord := uint32(header[8])<<8 | uint32(header[9])
header[8]--
newWord := uint32(header[8])<<8 | uint32(header[9])
incremental := ^add(^value&0xffff, ^oldWord&0xffff, newWord) & 0xffff
header[10], header[11] = 0, 0
fmt.Printf("\nafter the TTL change: incremental %04x, recomputed %04x\n",
incremental, checksum(header))
other, old, updated := uint32(0xcd7a), uint32(0x5555), uint32(0x3285)
value = ^add(other, old) & 0xffff
fmt.Printf("\nold checksum %04x, recomputed after the change %04x\n",
value, ^add(other, updated)&0xffff)
fmt.Printf("RFC 1141 shortcut, HC + m + ~m': %04x\n", add(value, old, ^updated&0xffff))
fixed := ^add(^value&0xffff, ^old&0xffff, updated) & 0xffff
fmt.Printf("RFC 1624 equation 3, ~(~HC + ~m + m'): %04x\n", fixed)
} Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go
Swift 6.4 · main.swift
func add(_ words: [UInt32]) -> UInt32 {
words.reduce(0) { total, word in
let next = total + word
return (next & 0xffff) + (next >> 16)
}
}
func wordsOf(_ data: [UInt8]) -> [UInt32] {
stride(from: 0, to: data.count, by: 2).map { index in
UInt32(data[index]) << 8 | (index + 1 < data.count ? UInt32(data[index + 1]) : 0)
}
}
func checksum(_ data: [UInt8]) -> UInt32 { ~add(wordsOf(data)) & 0xffff }
func hex(_ word: UInt32) -> String {
let digits = String(word, radix: 16)
return String(repeating: "0", count: 4 - digits.count) + digits
}
var header: [UInt8] = [
0x45, 0x00, 0x00, 0x3c, 0x1c, 0x46, 0x40, 0x00, 0x40, 0x06,
0x00, 0x00, 0xc0, 0x00, 0x02, 0x0a, 0xc6, 0x33, 0x64, 0x14,
]
print("words: ", wordsOf(header).map(hex).joined(separator: " "))
print("sum: " + hex(add(wordsOf(header))))
var value = checksum(header)
print("checksum: " + hex(value))
header[10] = UInt8(value >> 8)
header[11] = UInt8(value & 255)
print("receiver: the sum of all ten words, checksum included, is " + hex(add(wordsOf(header))))
let oldWord = UInt32(header[8]) << 8 | UInt32(header[9])
header[8] -= 1
let newWord = UInt32(header[8]) << 8 | UInt32(header[9])
let incremental = ~add([~value & 0xffff, ~oldWord & 0xffff, newWord]) & 0xffff
header[10] = 0
header[11] = 0
print(
"\nafter the TTL change: incremental \(hex(incremental)), "
+ "recomputed \(hex(checksum(header)))")
let other: UInt32 = 0xcd7a
let old: UInt32 = 0x5555
let updated: UInt32 = 0x3285
value = ~add([other, old]) & 0xffff
let recomputed = ~add([other, updated]) & 0xffff
print("\nold checksum \(hex(value)), recomputed after the change \(hex(recomputed))")
print("RFC 1141 shortcut, HC + m + ~m': " + hex(add([value, old, ~updated & 0xffff])))
let fixed = ~add([~value & 0xffff, ~old & 0xffff, updated]) & 0xffff
print("RFC 1624 equation 3, ~(~HC + ~m + m'): " + hex(fixed)) Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main
Ruby 4.0 · main.rb
# frozen_string_literal: true
def add(words)
words.reduce(0) do |total, word|
value = total + word
(value & 0xffff) + (value >> 16)
end
end
def words_of(data)
data.each_slice(2).map { |high, low| (high << 8) | (low || 0) }
end
def checksum(data)
~add(words_of(data)) & 0xffff
end
def hex(word)
format('%04x', word)
end
header = '4500003c1c46400040060000c000020ac6336414'.scan(/../).map { |byte| byte.to_i(16) }
puts "words: #{words_of(header).map { |word| hex(word) }.join(' ')}"
puts "sum: #{hex(add(words_of(header)))}"
value = checksum(header)
puts "checksum: #{hex(value)}"
header[10] = value >> 8
header[11] = value & 255
puts "receiver: the sum of all ten words, checksum included, is #{hex(add(words_of(header)))}"
old_word = (header[8] << 8) | header[9]
header[8] -= 1
new_word = (header[8] << 8) | header[9]
incremental = ~add([~value & 0xffff, ~old_word & 0xffff, new_word]) & 0xffff
header[10] = 0
header[11] = 0
puts "\nafter the TTL change: incremental #{hex(incremental)}, " \
"recomputed #{hex(checksum(header))}"
other = 0xcd7a
old = 0x5555
updated = 0x3285
value = ~add([other, old]) & 0xffff
recomputed = ~add([other, updated]) & 0xffff
puts "\nold checksum #{hex(value)}, recomputed after the change #{hex(recomputed)}"
puts "RFC 1141 shortcut, HC + m + ~m': #{hex(add([value, old, ~updated & 0xffff]))}"
fixed = ~add([~value & 0xffff, ~old & 0xffff, updated]) & 0xffff
puts "RFC 1624 equation 3, ~(~HC + ~m + m'): #{hex(fixed)}" Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb
Kotlin 2.4 · Main.kt
fun add(words: List<Int>): Int =
words.fold(0) { total, word ->
val next = total + word
(next and 0xffff) + (next ushr 16)
}
fun wordsOf(data: List<Int>): List<Int> {
val result = data.chunked(2).map { pair -> (pair[0] shl 8) or pair.getOrElse(1) { 0 } }
return result
}
fun checksum(data: List<Int>): Int = add(wordsOf(data)).inv() and 0xffff
fun hex(word: Int): String = word.toString(16).padStart(4, '0')
fun main() {
val data =
"4500003c1c46400040060000c000020ac6336414".chunked(2).map { it.toInt(16) }.toMutableList()
println("words: " + wordsOf(data).joinToString(" ") { hex(it) })
println("sum: " + hex(add(wordsOf(data))))
var value = checksum(data)
println("checksum: " + hex(value))
data[10] = value ushr 8
data[11] = value and 255
println(
"receiver: the sum of all ten words, checksum included, is " +
hex(add(wordsOf(data))),
)
val oldWord = (data[8] shl 8) or data[9]
data[8] = data[8] - 1
val newWord = (data[8] shl 8) or data[9]
val row = listOf(value.inv() and 0xffff, oldWord.inv() and 0xffff, newWord)
val delta = add(row).inv() and 0xffff
data[10] = 0
data[11] = 0
println(
"\nafter the TTL change: incremental ${hex(delta)}, " +
"recomputed ${hex(checksum(data))}",
)
val other = 0xcd7a
val old = 0x5555
val updated = 0x3285
value = add(listOf(other, old)).inv() and 0xffff
val total = add(listOf(other, updated)).inv() and 0xffff
println("\nold checksum ${hex(value)}, recomputed after the change ${hex(total)}")
val raw = add(listOf(value, old, updated.inv() and 0xffff))
println("RFC 1141 shortcut, HC + m + ~m': " + hex(raw))
val last = listOf(value.inv() and 0xffff, old.inv() and 0xffff, updated)
val done = add(last).inv() and 0xffff
println("RFC 1624 equation 3, ~(~HC + ~m + m'): " + hex(done))
} Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar
Dart 3.13 · main.dart
int add(List<int> words) {
var total = 0;
for (final word in words) {
total += word;
total = (total & 0xffff) + (total >> 16);
}
return total;
}
List<int> wordsOf(List<int> data) {
final words = <int>[];
for (var index = 0; index < data.length; index += 2) {
words.add(
data[index] << 8 | (index + 1 < data.length ? data[index + 1] : 0),
);
}
return words;
}
int checksum(List<int> data) => ~add(wordsOf(data)) & 0xffff;
String hex(int word) => word.toRadixString(16).padLeft(4, '0');
void main() {
final header = RegExp('..')
.allMatches('4500003c1c46400040060000c000020ac6336414')
.map((match) => int.parse(match.group(0) ?? '00', radix: 16))
.toList();
print('words: ${wordsOf(header).map(hex).join(' ')}');
print('sum: ${hex(add(wordsOf(header)))}');
var value = checksum(header);
print('checksum: ${hex(value)}');
header[10] = value >> 8;
header[11] = value & 255;
print(
'receiver: the sum of all ten words, checksum included, is '
'${hex(add(wordsOf(header)))}',
);
final oldWord = header[8] << 8 | header[9];
header[8] -= 1;
final newWord = header[8] << 8 | header[9];
final incremental =
~add([~value & 0xffff, ~oldWord & 0xffff, newWord]) & 0xffff;
header[10] = header[11] = 0;
print(
'\nafter the TTL change: incremental ${hex(incremental)}, '
'recomputed ${hex(checksum(header))}',
);
const other = 0xcd7a, old = 0x5555, updated = 0x3285;
value = ~add([other, old]) & 0xffff;
print(
'\nold checksum ${hex(value)}, recomputed after the change '
'${hex(~add([other, updated]) & 0xffff)}',
);
print(
"RFC 1141 shortcut, HC + m + ~m': "
'${hex(add([value, old, ~updated & 0xffff]))}',
);
final fixed = ~add([~value & 0xffff, ~old & 0xffff, updated]) & 0xffff;
print("RFC 1624 equation 3, ~(~HC + ~m + m'): ${hex(fixed)}");
} Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart
What every language printed
words: 4500 003c 1c46 4000 4006 0000 c000 020a c633 6414 sum: cddb checksum: 3224 receiver: the sum of all ten words, checksum included, is ffff after the TTL change: incremental 3324, recomputed 3324 old checksum dd2f, recomputed after the change 0000 RFC 1141 shortcut, HC + m + ~m': ffff RFC 1624 equation 3, ~(~HC + ~m + m'): 0000
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. Runs on this device: a JavaScript build of this program (about 66 KB), made when the page was built. The first run also downloads the JavaScript runner (about 0.6 MB), which is kept for the next runs. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 152 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a .NET build of this program (about 3 KB), made when the page was built. The first run also downloads .NET (about 3.6 MB), which is kept for the next runs. Edit runs your changes in the browser: the first edited run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 8 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads PHP (about 4.3 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 21 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads the JavaScript runner (about 0.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 720 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 1.7 MB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads Ruby (about 10.2 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 189 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 16 KB), made when the page was built. To change the code, copy it and run it with the command below.Your run, in this browser
The header’s ten words sum to 0xCDDB, so the checksum is 0x3224, and the receiver’s sum over all ten words comes out at 0xFFFF. That is no coincidence: adding any number to its own complement sets every bit, and in ones’ complement arithmetic checksum zero representations: The all-zero and all-one representations of zero in ones' complement arithmetic, which an incremental checksum formula must handle consistently with recomputation..
Follow the original CDDB sum to 3224 and FFFF while keeping a passing checksum separate from an unchanged-header claim.
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- The authored IPv 4 header has its checksum field zero while the sender adds its ten words.
- The carry is added back into the low sixteen bits; the original sum becomes CDDB.
- The complement 3224 makes the received header, checksum included, sum to FFFF. Passing that relation is not proof of unchanged bytes.
Checkpoint
Check: End-around carry forms the Internet checksum
An incremental checksum update must respect both zeros
The IPv4 checksum covers only the header, and an ordinary forwarding router recomputes or incrementally updates it, because the router changes a field: it lowers the time to live (TTL) by one. Rather than sum the whole header again, a router can update the checksum from the change alone. RFC 1624 gives the formula, with HC the old checksum, m the old 16-bit word and m′ the new one, and ~ the complement:
In the run, the TTL went from 64 to 63, so the word 0x4006 became 0x3F06, and the incremental update and the full recomputation both gave 0x3324. The last three lines replay RFC 1624’s own example of why the formula is written this way. The older shortcut of RFC 1141, HC + m + ~m′, gives 0xFFFF where the correct checksum is 0x0000. Both mean zero to a receiver that sums the whole header and compares the total with 0xFFFF, as RFC 1071 recommends, but an implementation that recomputes the checksum and compares it with the field rejects a good packet.
IPv6 dropped the header checksum altogether. RFC 8200 requires a UDP checksum by default (IPv4 permits omission); specifically constrained UDP tunnel modes have exceptions. RFC 8200 also notes that the fields of the IPv6 header are “not covered by an internet-layer checksum”: the link’s CRC protects each hop, and the transport checksum, which also covers the addresses, protects the whole path. Routers no longer have a checksum to update at all.
Compare original 3324 recomputation with the separate FFFF/0000 zero-boundary counterexample.
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- The original router change replaces word 4006 with 3 F 06 while keeping the remaining authored header words.
- The complement-based RFC 1624 equation agrees with full recomputation at 3324 on the original TTL change.
- The original RFC example shows the older shortcut returns FFFF where recomputation returns 0000, exposing the two zero representations.
Checkpoint
Check: An incremental checksum update must respect both zeros
Word order and cancelling changes can preserve a checksum
The Internet checksum is cheap: one addition per 16-bit word, in any order. RFC 1071 lists that order independence as a feature, because it lets implementations add words in parallel or in whichever byte order the computer uses. It is also the checksum’s weakness:
"""What the Internet checksum cannot see: words in another order, and some pairs of flipped bits."""
from itertools import combinations
# The header of internet_checksum.py, with its checksum 3224 filled in.
header = bytes.fromhex("4500 003c 1c46 4000 4006 3224 c000 020a c633 6414")
def add(*words):
total = 0
for w in words:
total += w
total = (total & 0xFFFF) + (total >> 16)
return total
def passes(data):
"""The receiver's test: the ones' complement sum of every word, checksum included, is FFFF."""
return add(*(data[i] << 8 | data[i + 1] for i in range(0, len(data), 2))) == 0xFFFF
def flip(data, *positions):
"""A copy of the data with the given bits flipped (bit 0 is the first bit sent)."""
out = bytearray(data)
for p in positions:
out[p // 8] ^= 0x80 >> (p % 8)
return bytes(out)
print("as sent:", passes(header))
swapped = header[:12] + header[16:20] + header[12:16] # source and destination addresses trade places
print("addresses swapped:", passes(swapped))
bits = len(header) * 8
singles = [p for p in range(bits) if passes(flip(header, p))]
print(f"\n{bits} single-bit errors, undetected: {len(singles)}")
pairs = list(combinations(range(bits), 2))
missed = [(a, b) for a, b in pairs if passes(flip(header, a, b))]
print(f"{len(pairs):,} two-bit errors, undetected: {len(missed):,} ({len(missed) / len(pairs):.1%})")
same_column = all(a % 16 == b % 16 for a, b in missed)
opposite = all((header[a // 8] >> (7 - a % 8) & 1) != (header[b // 8] >> (7 - b % 8) & 1) for a, b in missed)
print("all of them hit the same bit position in two different words:", same_column)
print("all of them turn one 0 into 1 and one 1 into 0:", opposite)
a, b = missed[0]
print(f"the first: position {a % 16} (counting from the left, from 0) of word {a // 16} and of word {b // 16}") Output
as sent: True addresses swapped: True 160 single-bit errors, undetected: 0 12,720 two-bit errors, undetected: 260 (2.0%) all of them hit the same bit position in two different words: True all of them turn one 0 into 1 and one 1 into 0: True the first: position 0 (counting from the left, from 0) of word 0 and of word 6
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 checksum_blind_spots.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Swapping the source and destination addresses changes the header completely and leaves the sum untouched. Every one of the 160 single-bit errors was detected, but 260 of the 12,720 two-bit errors, 2.0 %, were not, and all of them had the same shape: the same bit position in two different words, one changing from 0 to 1 and the other from 1 to 0. One word grew by while the other shrank by , so the sum stayed the same.
A CRC has no such blind spots for errors this small. The 32-bit CRC of Ethernet keeps a minimum distance of at least 4 on frames of up to 12,144 bits, according to the measurements that RFC 3385 summarises, so it detects every one-, two- and three-bit error in any frame up to 1,518 bytes, the classic Ethernet maximum. That is why links check frames with CRCs, while the checksum stays in IP, UDP and TCP, where it is quick to compute and to update and where a CRC on the link has already caught most damage. The next lesson builds CRCs from scratch.
Error detection in the GATE CS syllabus
The cited CS syllabus lists error detection under the data link layer. For numerical answers, two results of this lesson carry most of the weight: a code with minimum distance d detects d − 1 errors and corrects ⌊(d − 1)/2⌋, and r Hamming check bits protect up to data bits, so m data bits need the smallest r with .
Keep the original 260 misses among 12720 pairs beside the word-order and cancelling-change explanations.
The drawing shows the whole scene; its 3 steps are listed below.
Every step as text
- The original ten-word header has 160 bit positions tested with every single-bit mask.
- The original exhaustive pair test considers 12720 masks;260 preserve the checksum relation.
- One word increases and another decreases at the same bit weight, so their contributions cancel. Swapping whole words also preserves their sum.
Checkpoint
Check: Word order and cancelling changes can preserve a checksum
Practice
Practice that adapts to you
Practise this lesson
13 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Exercise · Medium · Python
An Internet checksum and a Hamming decoder
Write the two functions of codes.py:
internet_checksum(data)takesbytesand returns the 16-bit Internet checksum as anint: add the data as 16-bit big-endian words in ones' complement arithmetic (a carry out of the top bit is added back at the bottom), then return the complement of the sum. An odd number of bytes is padded with one zero byte. For the lesson's IPv4 header,internet_checksum(bytes.fromhex("4500003c1c46400040060000c000020ac6336414"))returns0x3224.hamming74_decode(word)takes a Hamming(7,4) codeword as a string of seven"0"/"1"characters, positions 1 to 7 from the left (p1 p2 d1 p4 d2 d3 d4, even parity), corrects at most one flipped bit and returns the four data bitsd1 d2 d3 d4as a string:hamming74_decode("0110011")andhamming74_decode("0100011")both return"1011".
The sample tests import both functions from codes.py.
Starter code · codes.py
def internet_checksum(data):
"""Return the 16-bit Internet checksum (RFC 1071) of data, as an int."""
# Replace this line with your code.
return 0
def hamming74_decode(word):
"""Correct at most one flipped bit of a Hamming(7,4) codeword such as "0110011" and return its 4 data bits."""
# Replace this line with your code.
return word[:4] The sample tests · test_codes.py
from itertools import product
from codes import hamming74_decode, internet_checksum
HEADER = bytes.fromhex("4500003c1c46400040060000c000020ac6336414")
def encode(d1, d2, d3, d4):
"""Hamming(7,4) with even parity: positions 1 to 7 are p1 p2 d1 p4 d2 d3 d4."""
return "".join(str(b) for b in (d1 ^ d2 ^ d4, d1 ^ d3 ^ d4, d1, d2 ^ d3 ^ d4, d2, d3, d4))
def test_checksum_of_the_lesson_header():
"""gives 0x3224 for the IPv4 header of the lesson"""
assert internet_checksum(HEADER) == 0x3224
def test_header_with_its_checksum():
"""gives 0 when the data already holds its own checksum"""
assert internet_checksum(HEADER[:10] + bytes.fromhex("3224") + HEADER[12:]) == 0
def test_end_around_carry():
"""adds a carry out of the top bit back at the bottom"""
assert internet_checksum(bytes.fromhex("ffff0001")) == 0xFFFE
assert internet_checksum(bytes.fromhex("8000800080008000")) == 0xFFFD
def test_odd_length_is_padded():
"""pads an odd number of bytes with one zero byte"""
assert internet_checksum(b"\x01") == 0xFEFF
assert internet_checksum(b"\x01\x02\x03") == 0xFBFD
assert internet_checksum(b"") == 0xFFFF
def test_decode_without_errors():
"""returns the data bits of a codeword that arrived intact"""
assert hamming74_decode("0110011") == "1011"
assert hamming74_decode("0000000") == "0000"
assert hamming74_decode("1111111") == "1111"
def test_decode_corrects_any_single_flip():
"""corrects a flip in any of the 7 positions of all 16 codewords"""
for data in product((0, 1), repeat=4):
word = encode(*data)
expected = "".join(map(str, data))
assert hamming74_decode(word) == expected, word
for p in range(7):
damaged = word[:p] + ("1" if word[p] == "0" else "0") + word[p + 1 :]
assert hamming74_decode(damaged) == expected, damaged A hint
For the checksum, pad first (if len(data) % 2: data += b"\x00"), then add data[i] << 8 | data[i + 1] for every even i, folding the carry back after each addition with total = (total & 0xFFFF) + (total >> 16); the answer is ~total & 0xFFFF. For the decoder, XOR together the positions (1 to 7) of every "1" in the word: the result is 0 for a correct codeword and the position of the flipped bit otherwise.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.
Interview questions
What does a code’s minimum Hamming distance tell you? It is the smallest number of bits in which any two codewords differ, and it fixes what the code can do: with minimum distance d, every pattern of up to d − 1 flipped bits is detected, because it cannot turn one codeword into another, and up to ⌊(d − 1)/2⌋ flipped bits can be corrected by choosing the nearest codeword. A single parity bit has d = 2 (detects one error, corrects none), and Hamming(7,4) has d = 3 (corrects one, or detects two).
Why does a receiver add up an IPv4 header, checksum included, and expect 0xFFFF? The sender stored the complement of the sum of all the other words in the checksum field. Adding a number and its complement sets every bit, so an intact header sums to 0xFFFF, which is zero in ones’ complement arithmetic. A different total means the checksum relation fails; a passing total alone does not prove that the header was unchanged.
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Mid to senior
A router decrements the TTL of every IPv4 packet it forwards. Show how it can update the header checksum from the change alone, and explain what goes wrong with the obvious shortcut HC' = HC + m + ~m'.
-
Mid to staff
An application stores 64 KB records, each with a 16-bit Internet checksum, and corrupted records occasionally pass the check. Which corruptions can that checksum miss, roughly how often, and what would you replace it with?
Key takeaways
- A parity bit detects every odd number of flipped bits and misses every even number.
- Two-dimensional parity locates and corrects a single flipped bit; in the 5 × 5 block every 1-, 2- and 3-bit error was detected and 100 of 12,650 four-bit errors were missed.
- A code with minimum distance d detects up to d − 1 errors and corrects up to ⌊(d − 1)/2⌋, but not both at full strength at once.
- Hamming(7,4) puts check bits at positions 1, 2 and 4; the syndrome is the position of a single flipped bit, and two flipped bits are “corrected” into the wrong data.
- The Internet checksum is the complement of the ones’ complement sum of 16-bit words; an intact header sums to 0xFFFF, and routers update it with RFC 1624’s formula when the TTL changes.
- It misses reordered words and errors that cancel out, 2.0 % of all two-bit errors in the example header; links use CRCs, and IPv6 dropped its header checksum.
Terms in this lesson
- checksum zero representations
- The all-zero and all-one representations of zero in ones' complement arithmetic, which an incremental checksum formula must handle consistently with recomputation.
- code validity check
- A test that a received word belongs to a permitted code; a passing relation can still result from an undetected error that reaches another valid word.
- end-around carry
- Adding a carry beyond the word width back into the low-order bits, as required by the Internet checksum's ones' complement arithmetic.
- Hamming syndrome
- The combined outcomes of a Hamming code's parity checks; under its single-bit error assumption, the syndrome identifies the position to correct.
- minimum code distance
- The fewest differing positions between two distinct permitted codewords, used to derive detection and nearest-decoding bounds under stated error assumptions.
Corrections
- Scoped recovery, receiver checks and CRC residues to their stated models while retaining the original examples and workloads.
- Scoped distance guarantees to the chosen decoder and checksum observations to their error model, including the two representations of zero.
References
- Error Detecting and Error Correcting Codes (R. W. Hamming, Bell System Technical Journal, volume 29, number 2, pages 147–160) (Bell System Technical Journal (American Telephone and Telegraph Company))
- RFC 1071: Computing the Internet Checksum (RFC Editor (IETF))
- RFC 1624: Computation of the Internet Checksum via Incremental Update (RFC Editor (IETF))
- RFC 1141: Incremental Updating of the Internet Checksum (RFC Editor (IETF))
- RFC 791: Internet Protocol (the header checksum) (RFC Editor (IETF))
- RFC 8200: Internet Protocol, Version 6 (IPv6) Specification (upper-layer checksums) (RFC Editor (IETF))
- RFC 768: User Datagram Protocol (the optional UDP checksum of IPv4) (RFC Editor (IETF))
- RFC 5737: IPv4 Address Blocks Reserved for Documentation (RFC Editor (IETF))
- RFC 3385: Internet Protocol Small Computer System Interface (iSCSI) Cyclic Redundancy Check (CRC)/Checksum Considerations (RFC Editor (IETF))
- itertools: combinations() and product() (Python Software Foundation)
- GATE 2027 syllabus for Computer Science and Information Technology (CS) (IIT Madras (GATE 2027 organising institute))
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress