Skip to content

Instantly share code, notes, and snippets.

@aslilac
Last active August 20, 2021 09:10
Show Gist options
  • Save aslilac/aceba3b090f8148e1d1192b9a34b9921 to your computer and use it in GitHub Desktop.
Save aslilac/aceba3b090f8148e1d1192b9a34b9921 to your computer and use it in GitHub Desktop.
A JavaScript/TypeScript CRC32 implementation in only 18 lines of code.
// Copyright 2019 McKayla Washburn
// MIT License
// Feel free to use this however you want for whatever you want.
// Just note that the function returns a signed 32 bit number.
// This is a limitation of JavaScript's bitwise operators.
// If the value you are checking against is unsigned, then you
// can convert it to a signed 32 bit number by doing a bitshift of 0.
// Ex:
// valid >> 0 === crc32( input )
const poly = 0xEDB88320;
const lookup = new Uint32Array( 256 );
lookup.forEach( ( _, i, self ) => {
let crc = i;
for ( let bit = 0; bit < 8; bit++ ) {
crc = crc & 1
? crc >>> 1 ^ poly
: crc >>> 1;
}
self[ i ] = crc;
});
// TypeScript definition, for reference.
// export default function crc32( data: Buffer | Uint8Array | number[] ) {
export default function crc32( data ) {
const input = Uint8Array.from( data );
return ~input.reduce(
( crc, byte ) => lookup[ ( crc ^ byte ) & 0xFF ] ^ crc >>> 8,
0xFFFFFFFF
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment