发表于:2004-12-21 16:38:00
5楼
Private ReturnData(1) As Byte '定义数组,用于显示
----------------------
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) '每一个数据与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 '高低位数据排列方式:HiLo
CRC16Lo = CRC16Lo Xor CL
End If
Next Flag
Next I
ReturnData(0) = CRC16Hi 'CRC高位
ReturnData(1) = CRC16Lo 'CRC低位
CRC16 = ReturnData
End Function
-------------------------------
Private Sub Command1_Click() '验证程序
Dim comput() As Byte
ReDim comput(7) As Byte '使用时,只需根据数据长短改动此处数组的大小和内容即可
comput(0) = &H1B
comput(1) = &H5
comput(2) = &H1
comput(3) = &H0
comput(4) = &H51
comput(5) = &H2
comput(6) = &H0
comput(7) = &H1
Call CRC16(comput())
Label1.Caption = ReturnData(0)
Label2.Caption = ReturnData(1)
End Sub
此程序经VB验证可用,使用时在窗体上添加两个Label控件和一个Command控件,无须做任何其他更改,便可运行。校验码是0xA001。