CRCtable算法,宽度限制
CRC table algorithm in C, width limitation
我找到了一个易于使用的 CRC 算法实现 here。它包括基于 table 和按位算法。该代码似乎工作正常,但基于 table 的算法存在一个重要限制。这是相关代码:
unsigned long reflect (unsigned long crc, int bitnum) {
unsigned long i, j=1, crcout=0;
for (i=(unsigned long)1<<(bitnum-1); i; i>>=1) {
if (crc & i) crcout|=j;
j<<= 1;
}
return (crcout);
}
void generate_crc_table() {
// make CRC lookup table used by table algorithms
int i, j;
unsigned long bit, crc;
for (i=0; i<256; i++) {
crc=(unsigned long)i;
if (refin) crc=reflect(crc, 8);
crc<<= order-8;
for (j=0; j<8; j++) {
bit = crc & crchighbit;
crc<<= 1;
if (bit) crc^= polynom;
}
if (refin) crc = reflect(crc, order);
crc&= crcmask;
crctab[i]= crc;
}
}
unsigned long crctablefast (unsigned char* p, unsigned long len) {
// fast lookup table algorithm without augmented zero bytes, e.g. used in pkzip.
// only usable with polynom orders of 8, 16, 24 or 32.
unsigned long crc = crcinit_direct;
if (refin) crc = reflect(crc, order);
if (!refin) while (len--) crc = (crc << 8) ^ crctab[ ((crc >> (order-8)) & 0xff) ^ *p++];
else while (len--) crc = (crc >> 8) ^ crctab[ (crc & 0xff) ^ *p++];
if (refout^refin) crc = reflect(crc, order);
crc^= crcxor;
crc&= crcmask;
return(crc);
}
请注意 table 函数的代码注释说:
only usable with polynom orders of 8, 16, 24 or 32.
基于 table 的算法是否通常限制为八的倍数的宽度(尤其是 table 使用 16 位和 32 位 table 的算法)?
是否可以实现基于 table 的 CRC 算法,该算法接受 任何 CRC 宽度(不仅是 8 的倍数)?怎么样?
是的,您可以为任何宽度的多项式实施基于 table 的 CRC。有关基于 table 的实现示例,请参阅 crcany 的输出,例如 5 位、13 位和 31 位 CRC。
这没有什么棘手的。
我找到了一个易于使用的 CRC 算法实现 here。它包括基于 table 和按位算法。该代码似乎工作正常,但基于 table 的算法存在一个重要限制。这是相关代码:
unsigned long reflect (unsigned long crc, int bitnum) {
unsigned long i, j=1, crcout=0;
for (i=(unsigned long)1<<(bitnum-1); i; i>>=1) {
if (crc & i) crcout|=j;
j<<= 1;
}
return (crcout);
}
void generate_crc_table() {
// make CRC lookup table used by table algorithms
int i, j;
unsigned long bit, crc;
for (i=0; i<256; i++) {
crc=(unsigned long)i;
if (refin) crc=reflect(crc, 8);
crc<<= order-8;
for (j=0; j<8; j++) {
bit = crc & crchighbit;
crc<<= 1;
if (bit) crc^= polynom;
}
if (refin) crc = reflect(crc, order);
crc&= crcmask;
crctab[i]= crc;
}
}
unsigned long crctablefast (unsigned char* p, unsigned long len) {
// fast lookup table algorithm without augmented zero bytes, e.g. used in pkzip.
// only usable with polynom orders of 8, 16, 24 or 32.
unsigned long crc = crcinit_direct;
if (refin) crc = reflect(crc, order);
if (!refin) while (len--) crc = (crc << 8) ^ crctab[ ((crc >> (order-8)) & 0xff) ^ *p++];
else while (len--) crc = (crc >> 8) ^ crctab[ (crc & 0xff) ^ *p++];
if (refout^refin) crc = reflect(crc, order);
crc^= crcxor;
crc&= crcmask;
return(crc);
}
请注意 table 函数的代码注释说:
only usable with polynom orders of 8, 16, 24 or 32.
基于 table 的算法是否通常限制为八的倍数的宽度(尤其是 table 使用 16 位和 32 位 table 的算法)?
是否可以实现基于 table 的 CRC 算法,该算法接受 任何 CRC 宽度(不仅是 8 的倍数)?怎么样?
是的,您可以为任何宽度的多项式实施基于 table 的 CRC。有关基于 table 的实现示例,请参阅 crcany 的输出,例如 5 位、13 位和 31 位 CRC。
这没有什么棘手的。