4

Is there any function or example for VB.NET to calculate CRC32 of an string or Byte Array?

Filburt
  • 17,626
  • 12
  • 64
  • 115
Shahriyar
  • 1,483
  • 4
  • 24
  • 37

1 Answers1

15

Use this:

Private Sub Main()
    Crc32.ComputeChecksum(Encoding.UTF8.GetBytes("Some string")).Dump()
End Sub

Public Class Crc32
    Shared table As UInteger()

    Shared Sub New()
        Dim poly As UInteger = &Hedb88320UI
        table = New UInteger(255) {}
        Dim temp As UInteger = 0
        For i As UInteger = 0 To table.Length - 1
            temp = i
            For j As Integer = 8 To 1 Step -1
                If (temp And 1) = 1 Then
                    temp = CUInt((temp >> 1) Xor poly)
                Else
                    temp >>= 1
                End If
            Next
            table(i) = temp
        Next
    End Sub

    Public Shared Function ComputeChecksum(bytes As Byte()) As UInteger
        Dim crc As UInteger = &HffffffffUI
        For i As Integer = 0 To bytes.Length - 1
            Dim index As Byte = CByte(((crc) And &Hff) Xor bytes(i))
            crc = CUInt((crc >> 8) Xor table(index))
        Next
        Return Not crc
    End Function
End Class
Magnus
  • 45,362
  • 8
  • 80
  • 118
  • Helped a lot... Nice question and excellent answer.... +1 for both.. – Venu GoPal Nov 08 '20 at 19:00
  • @Magnus ... what is the difference, if I use instead of `Encoding.UTF8` to `Encoding.UTF7` or 'Encoding.UTF32` – Venu GoPal Nov 10 '20 at 14:42
  • 1
    @VenuGoPal You can find useful information about that here: https://javarevisited.blogspot.com/2015/02/difference-between-utf-8-utf-16-and-utf.html#axzz6dTQdmFYI but essentially it is how many bits it takes to represent a character. Different encodings do this differently. – Magnus Nov 11 '20 at 08:42