CRC32和CRC8校验代码,C语言版

CRC32使用的是查表法,CRC8使用的是按位计算法,在QT5.5.1下实现了代码,但是可以移植到其它平台同样可以运行。

CRC32

使用的CRC-32:
参数模型:x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1
多项式(hex):04C11DB7
计算CRC初始值(hex): FFFFFFFF
计算结果异或值(hex): FFFFFFFF

输入Ascii:123456789
结果(hex):CBF43926

CRC8

使用的CRC-8/MAXIM:
参数模型: x8+x5+x4+1
多项式(hex):31
计算CRC初始值(hex):00
计算结果异或值(hex): 00

输入Ascii:123456789
结果(hex):A1
参考计算网页:CRC(循环冗余校验)在线计算

#include 
#include 
using namespace std;
unsigned long CRC32Table[256];

static void CRC32TableCreate(void)
{
    unsigned int c;
    unsigned int i, j;

    for (i = 0; i < 256; i++) {
        c = (unsigned int)i;
        for (j = 0; j < 8; j++) {
            if (c & 1)
                c = 0xedb88320L ^ (c >> 1);
            else
                c = c >> 1;
        }
        CRC32Table[i] = c;
    }

}
static unsigned int CRC32Calculate(void *pBuf ,unsigned pBufSize)
{
    unsigned int retCRCValue=0xffffffff;
    unsigned char *pData;
    pData=(unsigned char *)pBuf;
     while(pBufSize--)
     {
         retCRCValue=CRC32Table[(retCRCValue ^ *pData++) & 0xFF]^ (retCRCValue >> 8);
     }
     return retCRCValue^0xffffffff;
}
static unsigned char CRC8Calculate(void *pBuf ,unsigned pBufSize)
{
    unsigned char retCRCValue=0x00;
    unsigned char *pData;
    int i=0;
    unsigned char pDataBuf=0;
  //  retCRCValue=0x01;
    pData=(unsigned char *)pBuf;
   // pDataBuf=pData[0];
   // cout<

     while(pBufSize--)
     {
         pDataBuf=*pData++;
         for(i=0;i<8;i++)
         {
             if((retCRCValue^(pDataBuf))&0x01)
             {

                 retCRCValue^=0x18;
                 retCRCValue>>=1;
                 retCRCValue|=0x80;
             //    printf("i=%d;retCRCValue=%x\n",i,retCRCValue);
             }
             else
             {
                   retCRCValue>>=1;
             //     printf("i=%d;retCRCValue=%x\n",i,retCRCValue);
             }
            pDataBuf>>=1;
         }

     }
     return retCRCValue;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    unsigned char Num[9]={'1','2','3','4','5','6','7','8','9'};
     CRC32TableCreate();
    cout<<"CRCCalculatValue:"<9)<printf("CRCCalculatValue:%x\n",CRC8Calculate(Num,9));
    return a.exec();
}

你可能感兴趣的:(C/C++语言,嵌入式开发)