Skip to content

Instantly share code, notes, and snippets.

@esromneb
Forked from Yaffle/gist:1287361
Created August 13, 2013 04:19
Show Gist options
  • Save esromneb/6217873 to your computer and use it in GitHub Desktop.
Save esromneb/6217873 to your computer and use it in GitHub Desktop.
// https://gist.github.com/Yaffle/1287361
var crc32table = null;
crc32 = function(s) {
s = String(s);
var polynomial = 0x04C11DB7,
initialValue = 0xFFFFFFFF,
finalXORValue = 0xFFFFFFFF,
crc = initialValue,
i, j, c;
var buildTable = function() {
var reverse = function (x, n) {
var b = 0;
while (n) {
b = b * 2 + x % 2;
x /= 2;
x -= x % 1;
n--;
}
return b;
};
crc32table = [];
for (i = 255; i >= 0; i--) {
c = reverse(i, 32);
for (j = 0; j < 8; j++) {
c = ((c * 2) ^ (((c >>> 31) % 2) * polynomial)) >>> 0;
}
crc32table[i] = reverse(c, 32);
}
};
if( !crc32table )
buildTable();
for (i = 0; i < s.length; i++) {
c = s.charCodeAt(i);
if (c > 255) {
throw new RangeError();
}
j = (crc % 256) ^ c;
crc = ((crc / 256) ^ crc32table[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
@esromneb
Copy link
Author

Updated a tiny bit to only compute table on first execution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment