Skip to content

Instantly share code, notes, and snippets.

@sbrown345
Forked from Yaffle/gist:1287361
Created March 13, 2013 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbrown345/5155089 to your computer and use it in GitHub Desktop.
Save sbrown345/5155089 to your computer and use it in GitHub Desktop.
function crc32(s/*, polynomial = 0x04C11DB7, initialValue = 0xFFFFFFFF, finalXORValue = 0xFFFFFFFF*/) {
s = String(s);
var polynomial = arguments.length < 2 ? 0x04C11DB7 : arguments[1],
initialValue = arguments.length < 3 ? 0xFFFFFFFF : arguments[2],
finalXORValue = arguments.length < 4 ? 0xFFFFFFFF : arguments[3],
crc = initialValue,
table = [], i, j, c;
function reverse(x, n) {
var b = 0;
while (n) {
b = b * 2 + x % 2;
x /= 2;
x -= x % 1;
n--;
}
return b;
}
for (i = 255; i >= 0; i--) {
c = reverse(i, 32);
for (j = 0; j < 8; j++) {
c = ((c * 2) ^ (((c >>> 31) % 2) * polynomial)) >>> 0;
}
table[i] = reverse(c, 32);
}
for (i = 0; i < s.length; i++) {
c = s.charCodeAt(i);
if (c > 255) {
throw new RangeError();
}
j = (crc % 256) ^ c;
crc = ((crc / 256) ^ table[j]) >>> 0;
}
return (crc ^ finalXORValue) >>> 0;
}
alert(crc32('test').toString(16));//D87F7E0C
alert(crc32('test', 0x04c11db7, 0, 0xFFFFFFFF).toString(16));//6C45EEF
alert(crc32('test', 0x04c11db7, 0xFFFFFFFF, 0).toString(16));//278081F3
alert(crc32('test', 0x04c11db7, 0, 0).toString(16));//F93BA110
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment