如何用vb实现CRC(循环码)校验?
最佳答案
STEP7编写的不好找,VB编写的网上多的是,呵呵!
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) - 1
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
'Debug.Print Str(i) & ":", CRC16Lo, CRC16Hi
Next Flag
'Debug.Print CRC16Lo, CRC16Hi
Next i
Dim ReturnData(1) As Byte
ReturnData(0) = CRC16Lo 'CRC低位
ReturnData(1) = CRC16Hi 'CRC高位
CRC16 = CStr(Hex(CRC16Hi)) & CStr(Hex(CRC16Lo))
End Function
-------------------------
调用方法如下:
Dim data(7) As Byte
data(0) = &H5
data(1) = &H1
data(2) = &H0
data(3) = &H0
data(4) = &H2
data(5) = &H3
data(6) = &H1
MsgBox CRC16(data)
提问者对于答案的评价:
正确。能否解释一下A001是什么意思?生成多项式应该是18005阿?
(crc-16)
原创文章,作者:more0621,如若转载,请注明出处:https://www.zhaoplc.com/plc276124.html