编辑代码

#include <stdio.h>
#include <stdlib.h>

// 函数ModBusCRC16计算
unsigned short ModBusCRC16(unsigned char *pbuf, int len)
{
    unsigned short CRC16;
    CRC16 = 0xFFFF;               //CRC寄存器初始值
    for (int i = 0; i < len; i++) //计算所有字节
    {
        CRC16 ^= pbuf[i];
        for (int j = 0; j < 8; j++)
        {
            unsigned short rightBit = (unsigned short)(CRC16 & 0x0001);
            CRC16 >>= 1;
            if (rightBit == 1)
            {
                CRC16 ^= 0xA001; //异或多项式---固定
            }
        }
    }
    return CRC16;
}

// 程序运行入口函数main()
void main(void)
{
    unsigned char testData[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    unsigned short CRC16 = 0;
    printf("\r\n要计算CRC的%d个数据\r\n", sizeof(testData));
    for (int i = 0; i < sizeof(testData); i++)
    {
        printf("%02X ", testData[i]);
    }
    CRC16 = ModBusCRC16(testData, sizeof(testData));
    printf("\r\nCRC16_MODBUS=%04X\r\n", CRC16);
    system("pause"); // 系统函数暂停
}