单片机CRC8检验C语言实现

来源:互联网 发布:软件的界面设计 编辑:程序博客网 时间:2024/06/03 18:40

CRC校验类型:CRC8/MAXIM

多项式:X8+X5+X4+1

Poly:0011 0001  0x31

高位放到后面就变成 1000 1100 0x8c

C现实代码:

unsigned char crc8_chk_value(unsigned char *message, unsigned char len)
{
    uint8 crc;
    uint8 i;
    crc = 0;
    while(len--)
    {
        crc ^= *message++;
        for(i = 0;i < 8;i++)
        {
            if(crc & 0x01)
            {
                crc = (crc >> 1) ^ 0x8c;
            }
                else crc >>= 1;
        }
    }
    return crc;
}


CRC校验类型:CRC16/Modbus  又称CRC16_1

多项式:X16+X15+X2+1 

Poly:1000 0000 0000 0101  0x8005

高位放到后面就变成 1010 0000 0000 0001  0xa001

C现实代码:

unsigned int crc_chk_value(unsigned char *message, unsigned int len)
{
    int i, j;
    unsigned int crc_value = 0xffff;
    unsigned int current = 0;

    for (i = 0; i < len; i++)
    {
        crc_value ^= *message++;
        for (j = 0; j < 8; j++)
        {
            if (crc_value & 0x0001)
                crc_value = crc_value >>1 ^ 0xA001;
            else
                crc_value >>= 1;
        }
    }
    return crc_value;
}

上述两个CRC算法均经过CRC calculation软件计算验证。

原创粉丝点击