作者sniperliao ()
看板Visual_Basic
标题[VB6 ] 分享 CRC-16 Function (自写)
时间Tue Dec 27 23:56:18 2005
分享一下,这是自己的写法 :)
呼叫方式
fcs=crc16b(欲计算之byte阵列)
例如 'a' 的 ASCII 为 97 = &H61
则
Dim a(3) as byte
a(0)=0
a(1)=97 '或是 a(1)=asc("a")
a(2)=0
a(3)=0
debug.print crc16b(a)
结果为 8145 (此为CRC16之FCS)
若 crc16b( [原本资料+FCS+16bit的零]byte阵列 ) = 0
代表资料无误
Function crc16b(data() As Byte) As String
Dim crch, crcl As Byte 'crch,crcl为crc16高低位
Dim becrch, becrcl As Byte '存放余值
Dim tmp As Byte '强迫数值为Byte用
Dim tmp1 As Integer
Dim nowp '目前计算位置
becrch = &HFF '初始皆是 11111111
becrcl = &HFF '同上
crcl = &H5 'CRC16 的计算式 X^16+X^15+X^2+1 = 11000000000000101 = H018005
crch = &H80 '同上,X^16不记入 所以是高位H80 低为H05
becrch = becrch And data(0)
becrcl = becrcl And data(1)
'载入欲计算阵列(0) (1)於高低位
nowp = 16 '因载入两阵列16bits
'所以nowp跳至16
Do Until nowp = (UBound(data) + 1) * 8 '运算直到nowp=阵列最後bit
If (becrch And &H80) = &H0 Then '若余值高位元的最高位为0
becrch = SHL(becrch, 1) '余值高位元左移1bits
If (becrcl And &H80) = &H80 Then '若余值低位元的最高位为1
becrch = becrch Or 1 '高位元最後值填入1
End If
becrcl = SHL(becrcl, 1) '余值低位元左移
tmp = 2 ^ (7 - (nowp) Mod 8) '取出下一值所需的二进制
If data(Int(nowp \ 8)) And tmp Then '若下一值(需补上的)为1
becrcl = becrcl Or 1 '余值低位元最後值填入1
End If
nowp = nowp + 1 '运算位置累加1
Else
becrch = SHL(becrch, 1) '余值高位元左移1bits
If (becrcl And &H80) = &H80 Then '若余值低位元的最高位为1
becrch = becrch Or 1 '高位元最後值填入1
End If
becrcl = SHL(becrcl, 1) '余值低位元左移
tmp = 2 ^ (7 - (nowp) Mod 8)
If data(Int(nowp \ 8)) And tmp Then '若下一值(需补上的)为1
becrcl = becrcl Or 1 '余值低位元最後值填入1
End If
nowp = nowp + 1 '运算位置累加1
becrch = becrch Xor crch '若最高位不是0
becrcl = becrcl Xor crcl '高低位皆对进行对应crc进行XOR
End If
Loop
'以下是fcs转成string回传
If Len(Hex(becrch)) < 2 Then
crc16b = crc16b & "0" & Hex(becrch)
ElseIf Hex(becrch) = 0 Then
crc16b = crc16b & "00"
Else
crc16b = crc16b & Hex(becrch)
End If
If Len(Hex(becrcl)) < 2 Then
crc16b = crc16b & "0" & Hex(becrcl)
ElseIf Hex(becrcl) = 0 Then
crc16b = crc16b & "00"
Else
crc16b = crc16b & Hex(becrcl)
End If
End Function
补上左移 Function 这是网路上找到的
Public Function SHL(ByVal OPR As Byte, ByVal n As Integer) As Byte
Dim BD As Byte
Dim I As Integer
BD = OPR
For I = 1 To n - 1
BD = (BD And &H7F) * 2
Next I
CF = BD And &H80
SHL = (BD And &H7F) * 2
End Function
--
★ NTIT 05' 运动会 (详见下列Album)
Album =
http://www.wretch.cc/album/rmrug =
Guest Book =
http://gb1.demons.to/afgb.php?A=sniperliao =
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.221.15.86
※ 编辑: sniperliao 来自: 61.221.15.86 (12/28 00:00)