VB的CRC32校验代码

这几天编写了CRC32的VB代码,经测试于网上的CRC32校验验证结果完全相同。

Option Explicit
    Dim crc32Table(255) As Long
    
Private Sub Command1_Click()
    Dim strHex As String
    Dim i As Long
    Dim buffer() As Byte
    strHex = "AA 44 12 1C 2A 00 02 20 48 00 00 00 9D B4 29 07 B0 40 F8 20 00 00 10 00 00 00 01 00 00 00 00 00 32 00 00 00 18 8E 3D F1 67 B2 43 40 86 C3 7B 0F 36 30 5D 40 00 00 60 95 E5 38 03 40 00 00 00 00 3D 00 00 00 6D 87 D4 3B 6D 87 D4 3B 60 61 7F 3C 30 30 30 34 00 00 80 3F 00 FC 6C 46 11 11 11 11 00 00 00 4B"
    'strHex = "AA 44 12 1C 2A 00 02 20 48 00 00 00 9D B4 29 07 10 4A F8 20 00 00 10 00 00 00 01 00 00 00 00 00 32 00 00 00 65 E4 5A DD 67 B2 43 40 56 19 C3 51 35 30 5D 40 00 00 E0 CC D9 26 03 40 00 00 00 00 3D 00 00 00 69 8C DA 3B 69 8C DA 3B B6 44 83 3C 30 30 30 34 00 00 00 00 00 2C 6D 46 11 11 11 11 00 00 00 4B"
    ReDim buffer(Len(strHex) \ 3)
    For i = 1 To Len(strHex) Step 3
        buffer((i - 1) / 3) = Val("&H" & Left(Mid(strHex, i, 3), 2))
    Next
'    Open "C:\ts.bpm" For Binary As #1
'        Put #1, , buffer
'    Close #1
    Text1 = Right("00" & Hex(crc32byt(buffer)), 8)
    'MsgBox "Ok!"
End Sub

Public Function crc32byt(buf() As Byte) As Long
    Dim i As Long, iCRC As Long, lngA As Long, ret As Long
    Dim b() As Byte
    Dim bytT As Byte, bytC As Byte
    b = buf 'StrConv(item, vbFromUnicode)
    iCRC = &HFFFFFFFF
    InitCrc32
    For i = 0 To UBound(b)
        bytC = b(i)
        bytT = (iCRC And &HFF) Xor bytC
        lngA = ((iCRC And &HFFFFFF00) / &H100) And &HFFFFFF
        iCRC = lngA Xor crc32Table(bytT)
    Next
    ret = iCRC Xor &HFFFFFFFF
    crc32byt = ret
End Function

'CRC32 Table此段代码是CRC32表
Public Function InitCrc32(Optional ByVal Seed As Long = &HEDB88320, Optional ByVal Precondition As Long = &HFFFFFFFF) As Long
    Dim i As Integer, j As Integer, Crc32 As Long, Temp As Long
    For i = 0 To 255
        Crc32 = i
        For j = 0 To 7
            Temp = ((Crc32 And &HFFFFFFFE) / &H2) And &H7FFFFFFF
            If (Crc32 And &H1) Then Crc32 = Temp Xor Seed Else Crc32 = Temp
        Next
        crc32Table(i) = Crc32
    Next
    InitCrc32 = Precondition
End Function


你可能感兴趣的:(VB6源代码)