Created
April 7, 2023 19:47
-
-
Save bostrot/8f7892e7b0f9eaabaf481d5a4387e43b to your computer and use it in GitHub Desktop.
CRC32 Combine implementation from zlib in Dart
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
/// zlib crc32 combine implementation | |
/// Usage: | |
/// | |
/// CRC32().combine(checksum1, checksum2, length2); // length of part behind checksum2 | |
/// | |
class CRC32 { | |
List<int> x2ntable = List<int>.filled(32, 0); | |
CRC32() { | |
int n, p; | |
/* initialize the x^2^n mod p(x) table */ | |
p = 1 << 30; /* x^1 */ | |
x2ntable[0] = p; | |
for (n = 1; n < 32; n++) { | |
x2ntable[n] = p = multmodp(p, p); | |
} | |
} | |
static const int poly = 0xedb88320; | |
int combine(int crc1, int crc2, int length) { | |
return multmodp(x2nmodp(length, 3), crc1) ^ (crc2 & 0xffffffff); | |
} | |
/* | |
Return a(x) multiplied by b(x) modulo p(x), where p(x) is the CRC polynomial, | |
reflected. For speed, this requires that a not be zero. | |
*/ | |
int multmodp(int a, int b) { | |
int m, p; | |
m = 1 << 31; | |
p = 0; | |
for (;;) { | |
if ((a & m) != 0) { | |
p ^= b; | |
if ((a & (m - 1)) == 0) break; | |
} | |
m >>= 1; | |
if ((b & 1) != 0) { | |
b = (b >> 1) ^ poly; | |
} else { | |
b >>= 1; | |
} | |
} | |
return p; | |
} | |
/* | |
Return x^(n * 2^k) modulo p(x). Requires that x2n_table[] has been | |
initialized. | |
*/ | |
int x2nmodp(int n, int k) { | |
int p; | |
p = 1 << 31; | |
while (n != 0) { | |
if ((n & 1) != 0) p = multmodp(x2ntable[k & 31], p); | |
n >>= 1; | |
k++; | |
} | |
return p; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment