Created
October 12, 2022 05:44
-
-
Save diachedelic/582ac8fab84b7f2c34ff358ac5cc7cfa to your computer and use it in GitHub Desktop.
A CRC-32 checksum implementation for all JavaScript runtimes.
This file contains 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
// A CRC32 checksum implementation. It can be used to detect data corruption. | |
// The 'byte_array' parameter is a Uint8Array, the return value is a signed 32 | |
// bit integer. If you are checksumming a stream of data, pass the last known | |
// checksum as the 'checksum' parameter. | |
/*jslint bitwise */ | |
const table = (function () { | |
let values = new Int32Array(256); | |
let value_nr = 0; | |
while (value_nr < 256) { | |
let c = value_nr; | |
let iteration = 0; | |
while (iteration < 8) { | |
c = ( | |
c & 1 | |
? 0xEDB88320 ^ (c >>> 1) | |
: c >>> 1 | |
); | |
iteration += 1; | |
} | |
values[value_nr] = c; | |
value_nr += 1; | |
} | |
return values; | |
}()); | |
function crc32(byte_array, checksum = 0) { | |
checksum ^= 0xFFFFFFFF; | |
let byte_nr = 0; | |
while (byte_nr < byte_array.length) { | |
checksum = (checksum >>> 8) ^ table[ | |
(checksum ^ byte_array[byte_nr]) & 0xFF | |
]; | |
byte_nr += 1; | |
} | |
return checksum ^ 0xFFFFFFFF; | |
} | |
export default Object.freeze(crc32); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment