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.
Code
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"));Report a problem with this exampleOpens a pre-filled issue on GitHub.