Last active
March 5, 2022 04:16
-
-
Save JaosnHsieh/4d553999c4b4702e12e490dd857d1340 to your computer and use it in GitHub Desktop.
javascript incremental crc32 naive implementation.
This file contains hidden or 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
/** | |
* javascript incremental crc32 naive implementation. | |
* based on http://www.sunshine2k.de/articles/coding/crc/understanding_crc.html#ch44 | |
* not production ready, not efficient ! | |
dmeo:https://replit.com/join/dzezyxlpst-jaosnhsieh | |
* | |
* | |
*/ | |
// get correct values from open source lib | |
const { crc32 } = require('crc'); | |
const v1 = crc32(Buffer.from([0x01])); | |
const v2 = crc32(Buffer.from([0x02]), v1); | |
const v3 = crc32(Buffer.from([0x03]), v2); | |
console.log(`v1 ${v1} v2 ${v2} v3 ${v3}`); | |
//prepare own values | |
const tempCrc1 = getTempCrc32(Buffer.from([1])); | |
const vv1 = getFinalCrc(tempCrc1) >>> 0; | |
const tempCrc2 = getTempCrc32(Buffer.from([2]), tempCrc1); | |
const vv2 = getFinalCrc(tempCrc2) >>> 0; | |
const tempCrc3 = getTempCrc32(Buffer.from([3]), tempCrc2); | |
const vv3 = getFinalCrc(tempCrc3); | |
console.log(`vv1 ${vv1} vv2 ${vv2} vv3 ${vv3}`); | |
//test | |
const assert = require('assert'); | |
assert(v1 === vv1, 'vv1 error'); | |
console.log('vv1 passed!'); | |
assert(v2, vv2, 'vv2 error'); | |
console.log('vv2 passed!'); | |
assert(v3, vv3, 'vv3 error'); | |
console.log('vv3 passed!'); | |
// below crc32 implementation | |
function getFinalCrc(tempCrc) { | |
return ((libUtil_ReverseUint32(tempCrc) ^ 0xffffffff) & 0xffffffff) >>> 0; | |
} | |
function getTempCrc32(data = Buffer.from([]), previous = 0) { | |
let crc = previous !== 0 ? previous : 0xffffffff; | |
for (var j = 0; j < data.length; j++) { | |
let bin = data[j]; | |
let revBin = libUtil_ReverseUint8(bin); | |
crc ^= revBin << 24; | |
for (var i = 0; i < 8; i++) { | |
if (crc & 0x80000000) { | |
crc = (crc << 1) ^ 0x04c11db7; | |
} else { | |
crc = crc << 1; | |
} | |
revBin <<= 1; | |
} | |
} | |
return crc; | |
} | |
function libUtil_ReverseUint8(data = 0) { | |
var rval = 0; | |
var i = 0; | |
for (i = 0; i < 8; i++) { | |
if ((data & (1 << i)) != 0) { | |
rval |= 0x80 >> i; | |
} | |
} | |
return rval; | |
} | |
function libUtil_ReverseUint16(data = 0) { | |
return ( | |
(libUtil_ReverseUint8(data & 0xff) << 8) | | |
libUtil_ReverseUint8((data >> 8) & 0xff) | |
); | |
} | |
function libUtil_ReverseUint32(data = 0) { | |
return ( | |
(libUtil_ReverseUint16(data & 0xffff) << 16) | | |
libUtil_ReverseUint16((data >> 16) & 0xffff) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment