Is there any function or example for VB.NET to calculate CRC32 of an string or Byte Array?
Asked
Active
Viewed 1.8k times
4
-
1is [this](http://stackoverflow.com/questions/8128/how-do-i-calculate-crc32-of-a-string) what you needed.? – Rajaprabhu Aravindasamy Mar 21 '13 at 17:12
-
Actually i looked it before,But non of them works and most of those links was for Calculating CRC32 of a file – Shahriyar Mar 21 '13 at 17:20
-
1"non of them works" Really, whats wrong with them? – Magnus Mar 21 '13 at 17:29
1 Answers
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