Advertisement
s00rk

[VB.NET] CRC32

Oct 1st, 2011
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.87 KB | None | 0 0
  1. Public Class CRC32
  2.  
  3.     ' This is v2 of the VB CRC32 algorithm provided by Paul
  4.     ' (wpsjr1@succeed.net) - much quicker than the nasty
  5.     ' original version I posted.  Excellent work!
  6.  
  7.     Private crc32Table() As Integer
  8.     Private Const BUFFER_SIZE As Integer = 1024
  9.  
  10.     Public Function GetCrc32(ByRef stream As System.IO.Stream) As Integer
  11.  
  12.         Dim crc32Result As Integer
  13.         crc32Result = &HFFFFFFFF
  14.  
  15.         Dim buffer(BUFFER_SIZE) As Byte
  16.         Dim readSize As Integer = BUFFER_SIZE
  17.  
  18.         Dim count As Integer = stream.Read(buffer, 0, readSize)
  19.         Dim i As Integer
  20.         Dim iLookup As Integer
  21.         Dim tot As Integer = 0
  22.         Do While (count > 0)
  23.             For i = 0 To count - 1
  24.                 iLookup = (crc32Result And &HFF) Xor buffer(i)
  25.                 crc32Result = ((crc32Result And &HFFFFFF00) \ &H100) And &HFFFFFF   ' nasty shr 8 with vb :/
  26.                 crc32Result = crc32Result Xor crc32Table(iLookup)
  27.             Next i
  28.             count = stream.Read(buffer, 0, readSize)
  29.         Loop
  30.  
  31.         GetCrc32 = Not (crc32Result)
  32.  
  33.     End Function
  34.  
  35.     Public Sub New()
  36.  
  37.         ' This is the official polynomial used by CRC32 in PKZip.
  38.         ' Often the polynomial is shown reversed (04C11DB7).
  39.         Dim dwPolynomial As Integer = &HEDB88320
  40.         Dim i As Integer, j As Integer
  41.  
  42.         ReDim crc32Table(256)
  43.         Dim dwCrc As Integer
  44.  
  45.         For i = 0 To 255
  46.             dwCrc = i
  47.             For j = 8 To 1 Step -1
  48.                 If (dwCrc And 1) Then
  49.                     dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
  50.                     dwCrc = dwCrc Xor dwPolynomial
  51.                 Else
  52.                     dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
  53.                 End If
  54.             Next j
  55.             crc32Table(i) = dwCrc
  56.         Next i
  57.     End Sub
  58.  
  59. End Class
  60.  
  61.  
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement