Here 'tis.
Attribute VB_Name = "mathCRC32"
Option Explicit
Function CRC32Long(sInp As String) As Long
' UDF wrapper for iCRC32
' CRC32 is typically expressed as an unsigned Long, a data type that
' is not supported in VBA. So to see values between 0 and 2^32-1:
' =MOD(CRC32Hex("whatever"), 2^32)
CRC32Long = Right("0000000" & Hex(iCRC32(StrConv(sInp, vbFromUnicode))), 8)
End Function
Function CRC32Hex(sInp As String) As String
' UDF wrapper for iCRC32
' Returns an 8-character hex CRC32 string
CRC32Hex = Right("0000000" & Hex(iCRC32(StrConv(sInp, vbFromUnicode))), 8)
End Function
Function iCRC32(aiBuf() As Byte) As Long
' shg 2013, adapted from unkown source
Const iPoly As Long = &HEDB88320
Static bInit As Boolean
Static aiCRC(0 To 255) As Long
Dim iCRC As Long
Dim i As Long
Dim j As Long
Dim iLookup As Integer
If Not bInit Then
bInit = True
For i = 0 To 255
iCRC = i
For j = 8 To 1 Step -1
If iCRC And 1 Then
iCRC = ((iCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
iCRC = iCRC Xor iPoly
Else
iCRC = ((iCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
End If
Next j
aiCRC(i) = iCRC
Next i
End If
iCRC32 = &HFFFFFFFF
For i = LBound(aiBuf) To UBound(aiBuf)
iLookup = (iCRC32 And &HFF) Xor aiBuf(i)
' shift right 8 bits:
iCRC32 = ((iCRC32 And &HFFFFFF00) \ &H100) And &HFFFFFF
iCRC32 = iCRC32 Xor aiCRC(iLookup)
Next i
iCRC32 = Not iCRC32
End Function
Sub GetFileCRC()
Dim sFile As String
sFile = Application.GetOpenFilename(FileFilter:="All files, *.*", _
Title:="Pick a file")
If sFile = "False" Then Exit Sub
MsgBox Hex(iCRC32(ReadBinaryFile(sFile)))
End Sub
Function ReadBinaryFile(sFile As String) As Byte()
' Requires a reference to Microsoft ActiveX Data Objects
With New ADODB.Stream
.Type = adTypeBinary
.Open
.LoadFromFile sFile
ReadBinaryFile = .Read
End With
End Function
Bookmarks