1.計(jì)算法(以VB為例)
計(jì)算法就是依據(jù)CRC校驗(yàn)碼的產(chǎn)生原理來設(shè)計(jì)程序。其優(yōu)點(diǎn)是模塊代碼少,修改靈活,可移植性好。其缺點(diǎn)為計(jì)算量大。為了便于理解,這里假定了三位數(shù)據(jù),而多項(xiàng)式碼為A001(hex)。
在窗體上放置一命令按鈕Command1,并添加如下代碼:
Private Sub Command1_Click()
Dim CRC() As Byte
Dim d() As Byte ’待傳輸數(shù)據(jù)
ReDim d(2) As Byte
d(0) = 123
d(1) = 112
d(2) = 135
CRC = CRC16(d) ’調(diào)用CRC16計(jì)算函數(shù)
’CRC(0)為高位
’CRC(1)為低位
End Sub
注意:在數(shù)據(jù)傳輸時(shí)CRC的低位可能在前,而高位在后。
Function CRC16(data() As Byte) As String
Dim CRC16Lo As Byte, CRC16Hi As Byte ’CRC寄存器
Dim CL As Byte, CH As Byte ’多項(xiàng)式碼&HA001
Dim SaveHi As Byte, SaveLo As Byte
Dim I As Integer
Dim Flag As Integer
CRC16Lo = &HFF
CRC16Hi = &HFF
CL = &H1
CH = &HA0
For I = 0 To Ubound(data)
CRC16Lo = CRC16Lo Xor data(I) ’每一個(gè)數(shù)據(jù)與CRC寄存器進(jìn)行異或
For Flag = 0 To 7
SaveHi = CRC16Hi
SaveLo = CRC16Lo
CRC16Hi = CRC16Hi \ 2 ’高位右移一位
CRC16Lo = CRC16Lo \ 2 ’低位右移一位
If ((SaveHi And &H1) = &H1) Then ’如果高位字節(jié)最后一位為1
CRC16Lo = CRC16Lo Or &H80 ’則低位字節(jié)右移后前面補(bǔ)1
End If ’否則自動(dòng)補(bǔ)0
If ((SaveLo And &H1) = &H1) Then ’如果LSB為1,則與多項(xiàng)式碼進(jìn)行異或
CRC16Hi = CRC16Hi Xor CH
CRC16Lo = CRC16Lo Xor CL
End If
Next Flag
Next I
Dim ReturnData(1) As Byte
ReturnData(0) = CRC16Hi ’CRC高位
ReturnData(1) = CRC16Lo ’CRC低位
CRC16 = ReturnData
End Function