資源描述:
《CRC16校驗(yàn)算法實(shí)現(xiàn).doc》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫(kù)。
1、CRC16校驗(yàn)算法實(shí)現(xiàn)(轉(zhuǎn))循環(huán)冗余碼校驗(yàn)英文名稱為CyclicalRedundancyCheck,簡(jiǎn)稱CRC。它是利用除法及余數(shù)的原理來(lái)作錯(cuò)誤偵測(cè)(ErrorDetecting)的。實(shí)際應(yīng)用時(shí),發(fā)送裝置計(jì)算出CRC值并隨數(shù)據(jù)一同發(fā)送給接收裝置,接收裝置對(duì)收到的數(shù)據(jù)重新計(jì)算CRC并與收到的CRC相比較,若兩個(gè)CRC值不同,則說(shuō)明數(shù)據(jù)通訊出現(xiàn)錯(cuò)誤。根據(jù)應(yīng)用環(huán)境與習(xí)慣的不同,CRC又可分為以下幾種標(biāo)準(zhǔn):①CRC-12碼;②CRC-16碼;③CRC-CCITT碼;④CRC-32碼。CRC-12碼通常用來(lái)傳送6-bit字符串。CRC-16及CRC-CCITT碼則用是來(lái)傳送8
2、-bit字符,其中CRC-16為美國(guó)采用,而CRC-CCITT為歐洲國(guó)家所采用。CRC-32碼大都被采用在一種稱為Point-to-Point的同步傳輸中。下面著重是CRC-16檢驗(yàn)碼的生成過(guò)程。CRC-16碼由兩個(gè)字節(jié)構(gòu)成,在開(kāi)始時(shí)CRC寄存器的每一位都預(yù)置為1,然后把CRC寄存器與8-bit的數(shù)據(jù)進(jìn)行異或,之后對(duì)CRC寄存器從高到低進(jìn)行移位,在最高位(MSB)的位置補(bǔ)零,而最低位(LSB,移位后已經(jīng)被移出CRC寄存器)如果為1,則把寄存器與預(yù)定義的多項(xiàng)式碼進(jìn)行異或,否則如果LSB為零,則無(wú)需進(jìn)行異或。重復(fù)上述的由高至低的移位8次,第一個(gè)8-bit數(shù)據(jù)處理完畢,用
3、此時(shí)CRC寄存器的值與下一個(gè)8-bit數(shù)據(jù)異或并進(jìn)行如前一個(gè)數(shù)據(jù)似的8次移位。所有的字符處理完成后CRC寄存器內(nèi)的值即為最終的CRC值。下面為CRC16的計(jì)算過(guò)程,其中生成多項(xiàng)式為:X16+X15+X2+1:1.設(shè)置CRC寄存器,并給其賦值FFFF(hex)。2.將數(shù)據(jù)的第一個(gè)8-bit字符與16位CRC寄存器的低8位進(jìn)行異或,并把結(jié)果存入CRC寄存器。3.CRC寄存器向右移一位,MSB補(bǔ)零,移出并檢查L(zhǎng)SB。4.如果LSB為0,重復(fù)第三步;若LSB為1,CRC寄存器與生成多項(xiàng)式碼相異或。5.重復(fù)第3與第4步直到8次移位全部完成。此時(shí)一個(gè)8-bit數(shù)據(jù)處理完畢。6.
4、重復(fù)第2至第5步直到所有數(shù)據(jù)全部處理完成。7.最終CRC寄存器的內(nèi)容即為CRC值。?校驗(yàn)碼實(shí)現(xiàn)?編寫CRC校驗(yàn)程序有兩種辦法:一種為計(jì)算法,一種為查表法。下面是查表法的C語(yǔ)言實(shí)現(xiàn):校驗(yàn)碼算法程序?qū)崿F(xiàn)樣例(C語(yǔ)言):?//Test.cpp:Definestheentrypointfortheconsoleapplication.#include"stdafx.h"staticunsignedcharauchCRCHi[]={0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x8
5、1,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40
6、,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,
7、0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x01,0xC0,0x80,0x41,0x00,0xC1,0x81,0x40,0x00,0xC1