Skip to content

Instantly share code, notes, and snippets.

@mmis1000
Forked from Yaffle/gist:1287361
Last active December 21, 2015 17:59
Show Gist options
  • Save mmis1000/6343892 to your computer and use it in GitHub Desktop.
Save mmis1000/6343892 to your computer and use it in GitHub Desktop.
var crc32;
(function(){
var crcTableTable = [];
function buildTable(polynomial) {
var table = [];
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);
}
return table;
}
crc32 = function(s/*, polynomial = 0x04C11DB7, initialValue = 0xFFFFFFFF, finalXORValue = 0xFFFFFFFF*/) {
s = String(s);
var polynomial = arguments.length < 2 ? 0x04C11DB7 : arguments[1];
var initialValue = arguments.length < 3 ? 0xFFFFFFFF : arguments[2];
var finalXORValue = arguments.length < 4 ? 0xFFFFFFFF : arguments[3];
var crc = initialValue;
var table = [];
var i;
var j;
var c;
if(crcTableTable[polynomial]) {
table = crcTableTable[polynomial]
} else {
table = crcTableTable[polynomial] = buildTable(polynomial);
}
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
@mmis1000
Copy link
Author

cached the crc table to enhance the performance

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