Chapter 04 of 22 Part I: Foundations of Digital Information

The Incredible QR Code

5 Verified Book Snippets

Every .js file below is byte-identical (SHA-256 verified) to the printed code in Volume 1. Runnable blocks execute inside an isolated sandboxed iframe and Web Worker with a 2-second timeout and zero network access.

Download Chapter ZIP

block-01.js

Printed book snippet (byte-identical) · 153 bytes · SHA-256: b34cf439b54f…
Standalone runnable

Dependencies: None (standard ES2022 JavaScript). Runs directly in Node.js or the isolated browser sandbox and logs output.

function maskBit(bit, row, col) {
  return bit ^ Number((row + col) % 2 === 0);
}
console.log(maskBit(1, 4, 6)); // 0
console.log(maskBit(0, 4, 6)); // 1
Download .js

block-02.js

Printed book snippet (byte-identical) · 94 bytes · SHA-256: 72d456a23883…
Standalone runnable

Dependencies: None (standard ES2022 JavaScript). Runs directly in Node.js or the isolated browser sandbox and logs output.

const qr = encode("HELLO", "M");
console.log(qr.data);
console.log(qr.ecc);
console.log(qr.m);
Download .js

block-03.js

Printed book snippet (byte-identical) · 387 bytes · SHA-256: 032cc4bc2379…
Fragment / Lab-dependent

Dependencies: Browser DOM or chapter Interactive Lab environment. Interacts with browser UI elements or dialogs; inspect alongside the chapter Interactive Lab.

function drawQR(qr, canvas) {
  const scale = 10;
  canvas.width = canvas.height = 29 * scale;
  const ctx = canvas.getContext("2d");
  ctx.fillStyle = "white";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "black";
  qr.m.forEach((row, y) => row.forEach((v, x) => {
    if (v) ctx.fillRect((x+4)*scale, (y+4)*scale,
                        scale, scale);
  }));
}
Download .js

block-04.js

Printed book snippet (byte-identical) · 232 bytes · SHA-256: 8a2ae43e29bc…
Standalone runnable

Dependencies: None (standard ES2022 JavaScript). Runs directly in Node.js or the isolated browser sandbox and logs output.

const qr = encode("HELLO", "M");
const damaged = qr.m.map(row => [...row]);
for (const i of [0, 8, 16, 24]) {
  const [y, x] = qr.positions[i];
  damaged[y][x] ^= 1;
}
console.log(decode(damaged, "M"));
// {text: "HELLO", errors: 4}
Download .js

block-05.js

Printed book snippet (byte-identical) · 401 bytes · SHA-256: 69d190823063…
Standalone runnable

Dependencies: None (standard ES2022 JavaScript). Runs directly in Node.js or the isolated browser sandbox and logs output.

const known = new Set(["LAB-01", "LAB-02"]);
const scans = new Map();
function verify(id) {
  if (!known.has(id)) return "Unknown identifier";
  const count = (scans.get(id) || 0) + 1;
  scans.set(id, count);
  return count === 1 ? "First recorded scan"
                     : "Repeated scan: investigate";
}
console.log(verify("LAB-01"));
console.log(verify("LAB-01"));
console.log(verify("LAB-99"));
Download .js