Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

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.

  • Intermediate
  • 30 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 30 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

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 parity bit on the letter K Python · original-parity/parity.py
"""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

One program · 14 languages One even-parity bit, and one or two flipped bits O(n) for an n-bit word

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

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.

Interactive · stage by stage Even parity detects odd numbers of flipped bits Compare the original one-flip failure with the two-flip accepted word before treating parity as an integrity relation.
Even parity detects odd numbers of flipped bits, step 3 of 3. Showing Letter K, One changed bit, Two changed bits. In focus: Two changed bits.Letter KData 1001011One changed bit10110110Two changed bits10110010

The drawing shows the whole scene; its 3 steps are listed below.

Every step as text
  1. The original seven data bits contain four ones, so even parity appends a zero and sends 10010110.
  2. The original one-flip record has an odd number of ones and the even-parity relation fails.
  3. 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

  1. Question 1 of 2 Does passing parity prove that the payload stayed unchanged?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: No, an even-weight error can preserve the relation

    The original two-flip output is an accepted damaged word. Only odd-weight changes necessarily toggle the parity relation.

  2. Question 2 of 2 The original seven-bit K payload needs one parity bit. How many bits are sent?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 8 bits

    Seven data bits plus one parity bit gives 8.

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:

A 5 x 5 grid of bits with one damaged bit; only its row check and its column check fail, so they point at it.10111ok01000fails11011ok00101ok00101okokokfailsokokchecks

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, and every error of up to four bits Python · original-two-d-parity/two_d_parity.py
"""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

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.

Interactive · stage by stage Row and column checks locate one flipped bit Locate one bit with the failed row/column, then compare the 100 original undetected rectangle masks.
Row and column checks locate one flipped bit, step 3 of 3. Showing Data block, One error, Four errors. In focus: Four errors.Data blockSixteen data bitsOne errorRow and column failFour errorsRectangle corners

The drawing shows the whole scene; its 3 steps are listed below.

Every step as text
  1. The original 4-by 4 payload receives four row checks, four column checks and one corner check.
  2. Under the single-error assumption, the failing row and column identify the changed bit.
  3. 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

  1. Question 1 of 2 Why can the four rectangle corners escape this validity check?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Each affected row and column has two changes

    Two changes preserve parity in every affected row and column. The original checker evaluates both rows and columns.

  2. Question 2 of 2 The original 16 data bits add four row checks, four column checks and one corner. How many check bits are added?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 9 bits

    Four plus four plus one gives 9 parity bits.

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:

detects up to d−1 flipped bits\text{detects up to } d-1 \text{ flipped bits} corrects up to ⌊d−12⌋ flipped bits\text{corrects up to } \left\lfloor \frac{d-1}{2} \right\rfloor \text{ flipped bits}

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 distance, found by brute force Python · original-distance/distance.py
"""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

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.

Interactive · stage by stage Minimum distance bounds detection and correction Read the detection and nearest-decoding bounds separately on the original distance 2,3 and 4 code families.
Minimum distance bounds detection and correction, step 3 of 3. Showing Valid codewords, Validity check, Nearest decoding. In focus: Nearest decoding.Valid codewordsClosest separation dValidity checkDetect up to d-1Nearest decodingFloor((d-1)/2)

The drawing shows the whole scene; its 3 steps are listed below.

Every step as text
  1. Minimum distance counts the fewest differing positions between two allowed codewords.
  2. Fewer than d flips cannot change one codeword into another, so code membership rejects those changed words.
  3. 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

  1. Question 1 of 2 What extra condition makes the correction bound useful?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Use the stated nearest-codeword decoder and bounded-error assumption

    The distance argument establishes unique nearest decoding within its correction radius. The detection bound does not turn into an equally large correction radius.

  2. Question 2 of 2 The original exercise gives minimum distance 5. How many flipped bits does nearest decoding guarantee it can correct?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 2 bits

    Floor((5 minus 1) divided by 2) is 2.

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): every single-bit error, and one double error Python · original-hamming74/hamming74.py
"""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

One program · 14 languages Hamming(7,4) corrects one flip and misreads two O(n) for an n-bit word

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)

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 2r−12^r - 1 positions, so they protect up to 2r−r−12^r - r - 1 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.

Interactive · stage by stage A Hamming syndrome locates a single-bit error Trace all seven single flips, then preserve the original 2-and 6 counterexample that decodes to 1001.
A Hamming syndrome locates a single-bit error, step 3 of 3. Showing Original 1011, Single flip, Two flips. In focus: Two flips.Original 1011Codeword 0110011Single flipSyndrome is its positionTwo flipsPositions 2 and 6

The drawing shows the whole scene; its 3 steps are listed below.

Every step as text
  1. The original Hamming(7,4) code stores checks at positions 1,2 and 4 and data at 3,5,6 and 7.
  2. The original seven one-bit cases produce syndromes 1 through 7 and recover 1011.
  3. 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

  1. Question 1 of 2 When does the syndrome directly name the damaged position?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Under the declared single-bit error assumption

    The seven original single-flip cases meet that assumption. The original 2-and 6 pair produces a misleading syndrome 4.

  2. Question 2 of 2 The original error pair is at positions 2 and 6. Their XOR syndrome is what decimal position?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 4 position

    Binary 010 XOR 110 is 100, which is 4.

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:

  1. Pair the bytes into 16-bit words, most significant byte first; an odd number of bytes gets one zero byte at the end.
  2. 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.).
  3. 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 checksum of an IPv4 header, computed, checked and updated Python · original-internet-checksum/internet_checksum.py
"""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

One program · 14 languages Internet checksum and the incremental-update boundary O(n) for an n-byte header

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

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.

Interactive · stage by stage End-around carry forms the Internet checksum Follow the original CDDB sum to 3224 and FFFF while keeping a passing checksum separate from an unchanged-header claim.
End-around carry forms the Internet checksum, step 3 of 3. Showing Original header, Folded sum, Complement. In focus: Complement.Original headerTen 16-bit wordsFolded sumCDDBComplementChecksum 3224

The drawing shows the whole scene; its 3 steps are listed below.

Every step as text
  1. The authored IPv 4 header has its checksum field zero while the sender adds its ten words.
  2. The carry is added back into the low sixteen bits; the original sum becomes CDDB.
  3. 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

  1. Question 1 of 2 What happens to a carry beyond bit 16?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: It is added back into the low 16 bits

    The original checksum uses end-around carry. Discarding the carry computes a different arithmetic rule.

  2. Question 2 of 2 A folded sum is decimal 65535 before complementing. What is its 16-bit complement as a decimal integer?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 0 integer

    All sixteen bits are one, so complementing yields zero.

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:

HC′=∼(∼HC+∼m+m′)HC' = \sim\!\left(\sim HC + \sim m + m'\right)

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.

Interactive · stage by stage An incremental checksum update must respect both zeros Compare original 3324 recomputation with the separate FFFF/0000 zero-boundary counterexample.
An incremental checksum update must respect both zeros, step 3 of 3. Showing TTL change, RFC 1624, Zero boundary. In focus: Zero boundary.TTL changeSixty-four to 63RFC 1624Result 3324Zero boundaryFFFF versus 0000

The drawing shows the whole scene; its 3 steps are listed below.

Every step as text
  1. The original router change replaces word 4006 with 3 F 06 while keeping the remaining authored header words.
  2. The complement-based RFC 1624 equation agrees with full recomputation at 3324 on the original TTL change.
  3. 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

  1. Question 1 of 2 Why compare an incremental update with recomputation on a zero-boundary fixture?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The two zero representations can expose a wrong shortcut

    The original RFC example exercises exactly that distinction. The original recomputation legitimately produces 0000.

  2. Question 2 of 2 The original TTL changes from 64 to 63. By how many is the TTL reduced?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 1 hop

    The forwarding example lowers the TTL by one.

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:

Every single-bit and two-bit error of one IPv4 header Python · original-checksum-blind-spots/checksum_blind_spots.py
"""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

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 2k2^k while the other shrank by 2k2^k, 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 2r−r−12^r - r - 1 data bits, so m data bits need the smallest r with 2r≥m+r+12^r \ge m + r + 1.

Keep the original 260 misses among 12720 pairs beside the word-order and cancelling-change explanations.

Interactive · stage by stage Word order and cancelling changes can preserve a checksum Keep the original 260 misses among 12720 pairs beside the word-order and cancelling-change explanations.
Word order and cancelling changes can preserve a checksum, step 3 of 3. Showing Original header, All two-bit masks, Cancelling changes. In focus: Cancelling changes.Original headerOne hundred sixty bitsAll two-bit masksTwelve thousand 720Cancelling changesSame bit weight

The drawing shows the whole scene; its 3 steps are listed below.

Every step as text
  1. The original ten-word header has 160 bit positions tested with every single-bit mask.
  2. The original exhaustive pair test considers 12720 masks;260 preserve the checksum relation.
  3. 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

  1. Question 1 of 2 Why can a word swap preserve this checksum?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Addition of these 16-bit words is order independent

    The same word multiset has the same one's-complement sum. The IPv 4 checksum explicitly covers the header words.

  2. Question 2 of 2 Ten original words each contain 16 bits. How many single-bit positions does the exhaustive test inspect?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 160 bits

    Ten times sixteen gives 160.

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.

  1. Question 1 of 13 A stated eleven-bit payload has one parity bit added. How many bits are sent?

    Type a number.

    Show the answer: Question 1 of 13

    Answer: 12 bits

    Eleven plus one gives 12.

  2. Question 2 of 13 Choose two rows and two columns from four of each. How many distinct four-corner rectangles is that?

    Type a number.

    Show the answer: Question 2 of 13

    Answer: 36 rectangles

    Six row pairs times six column pairs gives 36.

  3. Question 3 of 13 A code has minimum distance 7. What is its guaranteed nearest-codeword correction radius?

    Type a number.

    Show the answer: Question 3 of 13

    Answer: 3 bits

    Floor((7 minus 1) divided by 2) is 3.

  4. Question 4 of 13 Checks at weights 1 and 4 fail under a single-error assumption. What is the syndrome position?

    Type a number.

    Show the answer: Question 4 of 13

    Answer: 5 position

    One plus four gives position 5.

  5. Question 5 of 13 A two-word sum reaches decimal 65536. What is its folded value after end-around carry?

    Type a number.

    Show the answer: Question 5 of 13

    Answer: 1 integer

    The carry 1 is added to the low sixteen zero bits.

  6. Question 6 of 13 A stated hop changes TTL 32 to 31. By how many is it reduced?

    Type a number.

    Show the answer: Question 6 of 13

    Answer: 1 hop

    The difference is one; the checksum update still needs its own word arithmetic.

  7. Question 7 of 13 Four 16-bit words have how many distinct single-bit positions?

    Type a number.

    Show the answer: Question 7 of 13

    Answer: 64 bits

    Four times sixteen gives 64 positions.

  8. Question 8 of 13 A code has a minimum Hamming distance of 5. How many flipped bits can its receiver always correct?

    Type a number.

    Show the answer: Question 8 of 13

    Answer: 2 bits

    A code corrects up to ⌊(d − 1)/2⌋ errors: ⌊4/2⌋ = 2. With two flips the received word is still at distance 2 from the codeword sent and at least 3 from every other codeword, so the nearest codeword is the right one. The same code could instead detect up to d − 1 = 4 flipped bits.

  9. Question 9 of 13 A 7-bit character travels with one even-parity bit. Which damage does the receiver miss?

    Choose one answer.

    Show the answer: Question 9 of 13

    Answer: Any even number of flipped bits, such as two

    Each flip changes the count of 1s by one. An odd number of flips makes the count odd, which the check catches; an even number brings it back to even, which the check accepts. The two-flip line of parity.py shows it.

  10. Question 10 of 13 A Hamming(7,4) receiver gets the word 0111011 (positions 1 to 7 from the left). What is the syndrome, the position of the flipped bit?

    Type a number.

    Show the answer: Question 10 of 13

    Answer: 4

    The 1s are at positions 2, 3, 4, 6 and 7, and 2 XOR 3 XOR 4 XOR 6 XOR 7 = 4. Equivalently, only the check bit p4 fails. Flipping position 4 back gives 0110011, the codeword for the data 1011, as in hamming74.py.

  11. Question 11 of 13 Two-dimensional parity protects a block of bits with row and column parities. Which of these errors does it always detect?

    Choose every answer that is right.

    Show the answer: Question 11 of 13

    Answer:

    • Any three flipped bits
    • Any two flipped bits
    • Any single flipped bit

    Its minimum distance is 4, so every pattern of up to three flips is detected (parity.py checked all 2,625 of them in a 5 × 5 block). Four flips at the corners of a rectangle keep every row and column even: 100 of the 12,650 four-bit patterns got through.

  12. Question 12 of 13 Which change to an IPv4 header does the Internet checksum never detect?

    Choose one answer.

    Show the answer: Question 12 of 13

    Answer: Two of its 16-bit words trading places

    Addition does not care about order, so moving words around leaves the sum, and so the checksum, the same: in checksum_blind_spots.py the header with its source and destination addresses swapped still passed. Every single-bit error and every change of one word's value is caught.

  13. Question 13 of 13 Why must a router recompute or update the IPv4 header checksum of every packet it forwards?

    Choose one answer.

    Show the answer: Question 13 of 13

    Answer: It lowers the TTL, and the checksum covers the header that holds it

    RFC 791 has every router recompute and verify the header checksum because header fields such as the TTL change on the way. RFC 1624's formula updates it from the old and new value of the changed word; IPv6 has no header checksum, so its routers skip this work.

Exercise · Medium · Python

An Internet checksum and a Hamming decoder

Write the two functions of codes.py:

  • internet_checksum(data) takes bytes and returns the 16-bit Internet checksum as an int: 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")) returns 0x3224.
  • 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 bits d1 d2 d3 d4 as a string: hamming74_decode("0110011") and hamming74_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.

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.

  1. 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'.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. 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?

    Model answer, Pro. First step and follow-ups

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

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.