Cycle Redundancy Check 32 (CRC32).
Calculates unsigned 32 bit checksum for 0xEDB88320 polynomial.
Speed optimization is done through using pre-calculated values from lookup tables.
Performance totally depends on the hardware. Results below are made on a very basic hardware with NodeJS v18.16.0, IntelCore i5 1.6 GHz CPU and DDR3 RAM.
Processor | Rate | CRC32OPS | Input | Time |
---|---|---|---|---|
CRC32 | 1.2047 Gbit/s | 147059 | 10K random 1024-Bytes items | 68 msec |
CRC32Streams | 850.1594 Mbit/s | - | 100MB random data file | 941 msec |
class CRC32
// Browser and NodeJS compatible.
class CRC32Streams
// Depends on NodeJS "stream" module.
"@tsxper/crc32" package is originally written in TypeScript. TypeScript type definitions are included.
UTF8 characters are fully supported.
crc32.calculate('español sí');
None.
const crc32 = new CRC32();
crc32.calculate('crc32 test');
// or
crc32.forString('crc32 test');
const crc32 = new CRC32();
crc32.forBytes(new TextEncoder().encode('crc32 test'));
Buffer extends Uint8Array.
const crc32 = new CRC32();
crc32.forBuffer(new TextEncoder().encode('crc32 test'));
const crc32 = new CRC32Streams();
const checksum = await crc32.forFile(filePath);
See "Compatibility".
HTML Copy/Paste Example
This example also shows how to calculate CRC32 for ArrayBuffer.
<!DOCTYPE html>
<html>
<body>
<p>Calculating crc32 for text "hello crc32": <span id="placeholder"></span></p>
<div>
<input type="file" id="input" />
<p>CRC32 of the file: <span id="filecrc32"></span></p>
</div>
<script type="importmap">
{
"imports": {
"@tsxper/crc32": "https://www.unpkg.com/@tsxper/crc32@2.1.0/esm/CRC32.js"
}
}
</script>
<script type="module">
import { CRC32 } from "@tsxper/crc32";
const crc32 = new CRC32();
function handleString() {
const crc = crc32.calculate("hello crc32");
document.getElementById('placeholder').innerText = crc;
}
handleString();
const fileInput = document.getElementById("input");
fileInput.addEventListener("change", handleFiles, false);
function handleFiles(e) {
if (!this.files.length) return;
const file = this.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const buffer = e.target.result; // ArrayBuffer
const view = new Uint8Array(buffer);
document.getElementById('filecrc32').innerText = crc32.forBytes(view);
};
reader.readAsArrayBuffer(file);
}
</script>
</body>
</html>
For example, for sequence of events, converted into Uint8Array[] chunks.
const chunks = [new TextEncoder().encode('text1 text2')];
const crc32 = new CRC32();
let crc = 0;
for (const chunk of chunks) {
crc = crc32.forBytes(chunk, crc);
}
const crc32 = new CRC32();
const checksum10 = crc32.calculate("hi"); // 3633523372
const checksum16 = `0x${checksum10.toString(16)}`; // 0xd8932aac
Both, CommonJS and ESM modules are supported.
import { CRC32 } from '@tsxper/crc32';
// or
const { CRC32 } = require('@tsxper/crc32');
Supporting of the both module systems is done through "import", "require" and "default" conditions.
MIT License.