|
這個校驗(yàn)方法是屬于CRC-8/MAXIM,多項(xiàng)式就是提到的X8+X5+X4+1(簡記31),CRC初值為0x00。其步驟如下所述:
1)初值CRC=0x00
2)CRC與待驗(yàn)數(shù)據(jù)異或并判斷最低位真假,若是真則執(zhí)行第3步,若是假執(zhí)行第4步
3)CRC與0x18異或再右移一位再與0x80按位或運(yùn)算,執(zhí)行第5步
4)CRC右移一位,執(zhí)行第5步
5)待驗(yàn)數(shù)據(jù)右移一位,執(zhí)行第6步
6)判斷第5步是否已經(jīng)執(zhí)行8次,若8次,本次計(jì)算結(jié)束,若沒夠8次,執(zhí)行第2步
這個步驟是對一個字節(jié)的校驗(yàn)。下面給出C的代碼,可對一串?dāng)?shù)據(jù)進(jìn)行校驗(yàn)。
#include <stdio.h>
#include <stdlib.h>
/*
函數(shù)名稱:get_crc
說 明:對數(shù)據(jù)幀進(jìn)行CRC-8MAXIM校驗(yàn),多項(xiàng)式31(簡記)
入 口:待校驗(yàn)數(shù)據(jù)字節(jié)地址msg,待校驗(yàn)數(shù)據(jù)個數(shù)msg_length
出 口:無
返 回:1個字節(jié)的CRC結(jié)果
*/
unsigned char get_crc(unsigned char *msg,unsigned char msg_length)
{
unsigned char crc=0;//初值
unsigned char data;//臨時數(shù)據(jù)變量
while (msg_length--)//待校驗(yàn)數(shù)據(jù)數(shù)量
{
data = *msg++;//更新需要檢驗(yàn)的數(shù)據(jù)
for (unsigned char i = 0;i < 8;i++)//一字節(jié)數(shù)據(jù)逐位校驗(yàn)
{
if((crc^(data))&0x01)
{
crc ^= 0x18;
crc >>= 1;
crc |= 0x80;
}
else
{
crc >>= 1;
}
data >>= 1;
}
}
return crc;
}
int main()
{
unsigned char crc = 0x01;
crc = get_crc(&crc,1);
printf("0x%02x\n",crc);//對0x01CRC8校驗(yàn),結(jié)果為0x5e
system("pause");
return 0;
}
手動演算的你按照步驟來,不會有錯的。有錯也是你不夠細(xì)心和沒有耐心。祝你好運(yùn)氣! |
|