CRC32 Checksum for Buffers and Strings

Compute CRC32 checksums for strings and byte arrays using a precomputed lookup table, with hex output for wire formats.

TypescriptData Integrity

Code

typescriptsnippet
32 lines
const TABLE = buildTable();

export function crc32(input: string | Uint8Array, seed = 0): number {
  const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
  if (!(bytes instanceof Uint8Array)) throw new TypeError("input must be a string or Uint8Array");
  if (!Number.isInteger(seed)) throw new TypeError("seed must be an integer");
  let crc = (seed ^ 0xffffffff) >>> 0;
  for (const byte of bytes) {
    crc = (TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8)) >>> 0;
  }
  return (crc ^ 0xffffffff) >>> 0;
}

export function crc32Hex(input: string | Uint8Array): string {
  return crc32(input).toString(16).padStart(8, "0");
}

function buildTable(): Uint32Array {
  const table = new Uint32Array(256);
  for (let index = 0; index < 256; index += 1) {
    let value = index;
    for (let bit = 0; bit < 8; bit += 1) {
      value = (value & 1) === 1 ? (value >>> 1) ^ 0xedb88320 : value >>> 1;
    }
    table[index] = value >>> 0;
  }
  return table;
}

console.log(crc32Hex("hello"));
console.log(crc32Hex(new TextEncoder().encode("hello")));
console.log(crc32Hex("The quick brown fox jumps over the lazy dog"));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

3610a686
3610a686
414fa339

How the snippet works

Structurally, expect the functions crc, crc32, crc32Hex and buildTable and nothing else.

Iteration is nested: for (const byte of bytes) frames the pass, for (let index = 0; index < 256; index += 1) does the per-item step. TypeError is the guard’s signal — thrown at the branch, before any partial work happens.

Applying it

The main signature reads export function crc32(input: string | Uint8Array, seed = 0)

The surface worth importing is crc32; the helpers around it are private to the snippet.

Statements that matter

if (!(bytes instanceof Uint8Array)) throw new TypeError("input must be a string or Uint8Array");
if (!Number.isInteger(seed)) throw new TypeError("seed must be an integer");
return crc32(input).toString(16).padStart(8, "0");

Interactive Tools for This Topic

FAQ

How does the snippet fail?
The code throws `TypeError`. Handle it at the call site or let it propagate deliberately.
What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `crc`, `crc32`, `crc32Hex` at load time.