CRC-CCITT16(0xFFFF、XModem、0x1D0F、Kermit) 原创

1、CCITT校验

ushort ccitt_16(const char *data, int len)
{
//    ushort crc16 = 0xFFFF;          // CRC-CCITT (0xFFFF)
//    ushort crc16 = 0x0000;            // CRC-CCITT (XModem)
    ushort crc16 = 0x1D0F;             // CRC-CCITT (0x1D0F)

    while( len-- )
    {
        for(uchar i=0x80; i!=0; i>>=1)
        {
            if((crc16 & 0x8000) != 0)
            {
                crc16 = crc16 << 1;
                crc16 = crc16 ^ 0x1021;
            }
            else
            {
                crc16 = crc16 << 1;
            }
            if((*data & i) != 0)
            {
                crc16 = crc16 ^ 0x1021;  //crc16 = crc16 ^ (0x10000 ^ 0x11021)
            }
        }
        data++;
    }

    return crc16;
}

//直接计算法计算CRC-CCITT (Kermit)
ushort ccitt16(const char *data, int len)
{
    int i;
    ushort crc = 0x0000;

    while(len--)
    {
        crc ^= *data++;
        for (i = 0; i < 8; ++i)
        {
            if (crc & 1)
                crc = (crc >> 1) ^ 0x8408;
            else
                crc = (crc >> 1);
        }
    }

    return crc;
}


// 验证
void MainWindow::on_pushButton_clicked()
{
    char arr[3] = {0x01, 0x02, 0x03};
    qDebug() << ccitt_16(arr, 3);
}

posted @ 2021-09-19 22:35  mahuifa  阅读(0)  评论(0编辑  收藏  举报  来源