mp;H1
CH = &HA0
For i = 0 To UBound(data)
CRC16Lo = CRC16Lo Xor data(i) ''每一个数据与CRC寄存器进行异或
For Flag = 0 To 7
SaveHi = CRC16Hi
SaveLo = CRC16Lo
CRC16Hi = CRC16Hi \ 2 ''高位右移一位
CRC16Lo = CRC16Lo \ 2 ''低位右移一位
If ((SaveHi And &H1) = &H1) Then ''如果高位字节最后一位为1
CRC16Lo = CRC16Lo Or &H80 ''则低位字节右移后前面补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
2.查表法
查表法的优缺点与计算法的正好相反。为了便于比较,这里所有的假定与计算法的完全相同,都而在窗体上放置一个Command1的按钮,其代码部分与上面的也完全一致。下面只介绍CRC函数的编写源代码。
Private Function CRC16(data() As Byte) As String
Dim CRC16Hi As Byte
Dim CRC16Lo As Byte
CRC16Hi = &HFF
CRC16Lo = &HFF
Dim i As Integer
Dim iIndex As Long
For i = 0 To UBound(data)
iIndex = CRC16Lo Xor data(i)
CRC16Lo = CRC16Hi Xor GetCRCLo(iIndex) ''低位处理
CRC16Hi = GetCRCHi(iIndex) ''高位处理
Next i
Dim ReturnData(1) As Byte
ReturnData(0) = CRC16Hi ''CRC高位
ReturnData(1) = CRC16Lo ''CRC低位
CRC16 = ReturnData
End Function
''CRC低位字节值表
Function GetCRCLo(Ind As Long) As Byte
GetCRCLo = Choose(Ind + 1, &H0, &HC1, &H81, &H40, &H1, &HC0, &H80, &H41, &H1, &HC0, &H80, &H41, &H0, &HC1, &H81, &H40, &H1, &HC0, &H80, &H41, &H0, &HC1, &H81, &H40, &H0, &HC1, &H81, &H40, &H1, &HC0, &H80, &H41, &H1, &HC0, &H80, &H41, &H0, &HC1, &H81, &H40, &H0, &HC1, &H81, &H40, &H1, &HC0, &H80, &H41, &H0, &HC1, &H81, &H40, &H1, &HC0, &H80, &H41, &H1, &HC0, &H80, &H41, &H0, &HC1, &H81, &H40, &H1, &HC0, &H80, &H41, &H0, &HC1, &H81, &H40, &H0, &HC1, &H81, &H40, &H1, &HC0, &H80, &H41, &H0, &HC1, &H81, &H40, &H1, &HC0, &H80, &H41, &H1, &HC0, &H80, &H41, &H0, &HC1, &H81, &H40, &H0, &HC1, &H81, &H40, &H1, &HC0, &H80, &H41, &H1, &HC0, &H80, &H41, &H0, &HC1, &H81, &H40, &H1, &HC0, &H80, &H41, &H0, &HC1, &H81, &H40, &H0, &HC1, &H81, &H40, &H1, &HC0, &H80, &H41