7,762
社区成员
发帖
与我相关
我的任务
分享
Public Function crc16z(ByVal txt As String, ByVal lon As Long) As Long
Dim flag As Long
Dim crc As Long
Dim car As Integer
Dim bit As Integer
Dim test As String
crc = &HFFFF&
For car = 1 To lon Step 2
crc = crc Xor getHex(Mid(txt, car, 2))
For bit = 0 To 7
flag = crc And 1&
crc = crc \ 2&
If flag = 1 Then crc = crc Xor &HA001&
Next
Next
crc16z = Int(crc And &HFFFF&)
End Function
Public Function getHex(ByVal inputString) As Byte
Dim ib As String
Dim returnValue
returnValue = 0
ib = UCase(Mid(inputString, 1, 1))
If ib = "0" Then returnValue = 0
If ib = "1" Then returnValue = 16
If ib = "2" Then returnValue = 32
If ib = "3" Then returnValue = 48
If ib = "4" Then returnValue = 64
If ib = "5" Then returnValue = 80
If ib = "6" Then returnValue = 96
If ib = "7" Then returnValue = 112
If ib = "8" Then returnValue = 128
If ib = "9" Then returnValue = 144
If ib = "A" Then returnValue = 160
If ib = "B" Then returnValue = 176
If ib = "C" Then returnValue = 192
If ib = "D" Then returnValue = 208
If ib = "E" Then returnValue = 224
If ib = "F" Then returnValue = 240
ib = UCase(Mid(inputString, 2, 1))
If ib = "0" Then returnValue = returnValue + 0
If ib = "1" Then returnValue = returnValue + 1
If ib = "2" Then returnValue = returnValue + 2
If ib = "3" Then returnValue = returnValue + 3
If ib = "4" Then returnValue = returnValue + 4
If ib = "5" Then returnValue = returnValue + 5
If ib = "6" Then returnValue = returnValue + 6
If ib = "7" Then returnValue = returnValue + 7
If ib = "8" Then returnValue = returnValue + 8
If ib = "9" Then returnValue = returnValue + 9
If ib = "A" Then returnValue = returnValue + 10
If ib = "B" Then returnValue = returnValue + 11
If ib = "C" Then returnValue = returnValue + 12
If ib = "D" Then returnValue = returnValue + 13
If ib = "E" Then returnValue = returnValue + 14
If ib = "F" Then returnValue = returnValue + 15
getHex = returnValue
End Function
Public Function crc16z(ByVal txt As String, ByVal lon As Long) As Long
Dim flag As Long
Dim crc As Long
Dim car As Integer
Dim bit As Integer
Dim test As String
crc = &HFFFF& '设置 CRC 的初始值
For car = 1 To lon Step 2 '循环提取字符串中的字符,每次 2 字符(表示一个 16 进制码)
'相当于 for(i=1;i<=lon;i+=2)
crc = crc Xor getHex(Mid(txt, car, 2)) 'CRC 与一个十六进制数异或
'getHex 将字符转为数字,Mid 与 CString.Mid 相当
For bit = 0 To 7 '内循环,对每一比特处理,相当于 for(j=0;j<8;j++)
flag = crc And 1& '保存最低比特
crc = crc \ 2& 'CRC 右移一位,相当于 crc >>= 1;
If flag = 1 Then crc = crc Xor &HA001& 'if(flag) crc ^= 0xa001;
Next 'VB 特有的,相当于 for(j=0;j<0;j++) 后面的 }
Next 'VB 特有的,相当于 for(i=0;i<=lon;j+=2) 后面的 }
crc16z = Int(crc And &HFFFF&) '相当于 return crc; 之所以要与 0xffff,是因为 VB 没有无符号数,编写者使用了 Long 来避免负数。但他忘了,对于位处理,正数和负数是一样的。
End Function