VB 语言CRC16校验算法
-----------------------------------------------------
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 '此处变为 0
CRC16Hi = &HFF '此处变为 0
CL = &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
---------------------------------------------------------