C中的CRC表算法,宽度限制

标签 c algorithm crc

我找到了一个易于使用的 CRC 算法实现 here .它包括基于表的算法和按位算法。该代码似乎工作正常,但基于表的算法存在一个重要限制。这是相关代码:

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);
}

请注意表函数的代码注释:

only usable with polynom orders of 8, 16, 24 or 32.

基于表格的算法是否通常限制为八的倍数的宽度(尤其是使用 16 位和 32 位表格的表格算法)?

是否有可能实现一个基于表格的 CRC 算法,该算法接受任何 CRC 宽度(不仅是 8 的倍数)?怎么办?

最佳答案

是的,您可以为任何宽度的多项式实现基于表格的 CRC。查看 crcany 的输出例如,5 位、13 位和 31 位 CRC 的基于表的实现。

这没有什么棘手的。

关于C中的CRC表算法,宽度限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40141505/

相关文章:

r - 过滤表以仅保留非冗余组

Java - 实现快速排序

c++ - 我如何优化/改进这个哈希函数

c - 如何防止用户键入错误的输入?

c - 无法理解C语言中的冒泡排序算法

javascript - CRC-16-IBM 实现 (JS) 不工作

algorithm - 简单的错误检查以替换闪存中的重复代码

c - C语言中如何计算crc8?

c - c 中的指针和函数

清除结构数组中的项目