1.計算法(以VB為例)
計算法就是依據(jù)CRC校驗碼的產(chǎn)生原理來設(shè)計程序。其優(yōu)點是模塊代碼少,修改靈活,可移植性好。其缺點為計算量大。為了便于理解,這里假定了三位數(shù)據(jù),而多項式碼為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計算函數(shù)
’CRC(0)為高位
’CRC(1)為低位
End Sub
注意:在數(shù)據(jù)傳輸時CRC的低位可能在前,而高位在后。
Function CRC16(data() As Byte) As String
Dim CRC16Lo As Byte, CRC16Hi As Byte ’CRC寄存器
Dim CL As Byte, CH As Byte ’多項式碼&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) ’每一個數(shù)據(jù)與CRC寄存器進行異或
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é)右移后前面補1
End If ’否則自動補0
If ((SaveLo And &H1) = &H1) Then ’如果LSB為1,則與多項式碼進行異或
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