Created
May 27, 2025 23:23
-
-
Save big-harry/850030280c28cd63d77922a0ef39c478 to your computer and use it in GitHub Desktop.
Calculating a CRC-32 algebraically in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is a port of https://github.com/Michaelangel007/crc32 | |
/** | |
* Calculates the CRC-32 of the data input | |
* @param {Int8Array) data | |
* @return {number | TypeError} - CRC-32 of the data input | |
*/ | |
function crc32(data) { | |
if (!(data instanceof Int8Array)) | |
return new TypeError("Int8Array input expected"); | |
var crc = -1 >>> 0; | |
const polynomial = 0xEDB88320 >>> 0; | |
for (const byte of data) { | |
crc ^= byte; | |
for (let bit = 8; bit--;) { | |
if (crc & 1) { | |
crc = (crc >>> 1) ^ polynomial; | |
} else { | |
crc >>>= 1; | |
} | |
} | |
} | |
return ~crc >>> 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment