CRC算法C语言实现查表法,支持配置多项式与初始值

本文详细介绍了循环冗余校验(CRC)算法,包括CRC-16的原理和C语言实现示例,以及如何使用crc32和crc16查表法计算,并提供了MODBUS场景下的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网络上CRC讲解很多优秀帖子:1的参考文献很厉害,且带有源码

1、一文详解循环冗余校验校验算法(CRC校验)及C语言代码的实现 ---- 以CRC-16/MODBUS为例讲解

2、CRC校验原理及其C语言实现

如下是c语言代码,支持crc32、crc16查表法计算代码,支持配置初始化值与多项式算法

void crc_init_crc32_table(unsigned int crc_poly, unsigned int *crc_table)
{
    unsigned int i;
    unsigned int j;

    for (i = 0; i < 256; i++) {
        unsigned int temp = i << 24;
        for (j = 0; j < 8; j++) {
            temp = (temp << 1) ^ (crc_poly * ((temp >> 31) & 0x1));
        }
        crc_table[i] = temp;
    }
}
void crc_init_crc16_table(short int crc_poly, short int *crc_table)
{
    unsigned int i;
    unsigned int j;

    for (i = 0; i < 256; i++) {
        short int temp = i << 8;
        for (j = 0; j < 8; j++) {
            temp = (temp << 1) ^ (crc_poly * ((temp >> 15) & 0x1));
        }
        crc_table[i] = temp;
    }
}

unsigned int crc_hash_calc_crc32(unsigned int init, unsigned int poly, uint8 *byte_input, unsigned int len)
{
    unsigned int loop = len;
    unsigned int crc_table[256] = { 0 };
    crc_init_crc32_table(poly, crc_table);

    unsigned int i;
    unsigned int temp;
    unsigned int crc_val = init;
    unsigned int old_crc;
    unsigned int input;
    for (i = 0; i < loop; i++) {
        input = byte_input[i];
        crc_val = crc_val ^ (input << 24);
        temp = crc_val >> 24;
        old_crc = crc_table[temp];
        crc_val = (crc_val << 8) ^ old_crc;
    }

    return crc_val;
}
unsigned int crc_hash_calc_crc16(unsigned int init, unsigned int poly, uint8 *byte_input, unsigned int len)
{
    unsigned int loop = len;
    short int crc_table[256] = { 0 };
    crc_init_crc16_table(poly, crc_table);

    short int i;
    short int temp;
    short int crc_val = init;
    short int old_crc;
    short int input;
    for (i = 0; i < loop; i++) {
        input = byte_input[i];
        crc_val = crc_val ^ (input << 8);
        temp = crc_val >> 8;
        old_crc = crc_table[temp];
        crc_val = (crc_val << 8) ^ old_crc;
    }

    return crc_val;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值