- UID
- 1
- 精华
- 积分
- 76365
- 威望
- 点
- 宅币
- 个
- 贡献
- 次
- 宅之契约
- 份
- 最后登录
- 1970-1-1
- 在线时间
- 小时
|
- Option Explicit
- Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
- Public g_CRC32_Table() As Long
- Private Function ShR1(ByVal Value As Long) As Long
- If Value >= 0 Then
- ShR1 = Value \ &H2&
- Else
- ShR1 = ((Value And &H7FFFFFFF) \ &H2&) Or &H40000000
- End If
- End Function
- Private Function ShR8(ByVal Value As Long) As Long
- If Value >= 0 Then
- ShR8 = Value \ &H100&
- Else
- ShR8 = ((Value And &H7FFFFFFF) \ &H100&) Or &H800000
- End If
- End Function
- Private Sub CRC32_GenTable()
- Erase g_CRC32_Table
- ReDim g_CRC32_Table(255)
- Dim I As Long, J As Long, Remainder As Long
- Const Polynomial As Long = &HEDB88320
- For I = 0 To 255
- Remainder = I
- For J = 0 To 7
- If Remainder And 1 Then
- Remainder = ShR1(Remainder) Xor Polynomial
- Else
- Remainder = ShR1(Remainder)
- End If
- Next
- g_CRC32_Table(I) = Remainder
- 'Debug.Print Hex8(Remainder); ", ";
- 'If I Mod 4 = 3 Then Debug.Print
- Next
- End Sub
- Sub CRC32_Init()
- On Local Error GoTo ErrHandler
- Dim ByteArray() As Byte
- ByteArray = LoadResData("CRC_TABLE", "BIN")
- ReDim g_CRC32_Table((UBound(ByteArray) + 1) / 4 - 1)
- CopyMemory g_CRC32_Table(0), ByteArray(0), UBound(ByteArray) + 1
- Exit Sub
- ErrHandler:
- CRC32_GenTable
- End Sub
- Function CRC32(ByVal CRC As Long, Data() As Byte) As Long
- On Local Error GoTo ErrHandler
- Dim I As Long
- Start:
- CRC32 = Not CRC
- For I = LBound(Data) To UBound(Data)
- CRC32 = g_CRC32_Table((CRC32 Xor Data(I)) And &HFF&) Xor ShR8(CRC32)
- Next
- CRC32 = Not CRC32
- Exit Function
- ErrHandler:
- If Err.Number = 9 Then
- Err.Clear
- CRC32_Init
- GoTo Start
- Else
- Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
- End If
- End Function
复制代码 其实CRC32需要的这个移位操作可以用整数除法实现。关键是:VB6的Long是有符号的,负数做除法的效果不同于移位,所以需要对负数做特殊处理。但总之,可以轻松实现。
CRC32需要CRC表,这个表可以直接做成RES资源,然后用LoadResData读出为Byte数组,再Copy成Long数组即可。
虽说这份代码会自动没有RES资源的时候,现场计算CRC表。
crc_table.zip
(1.16 KB, 下载次数: 9)
|
|