计算字符串或字节数组的CRC32 [复制](Calculate CRC32 of an String

2019-07-22 10:07发布

这个问题已经在这里有一个答案:

  • 如何计算字符串的CRC32 2个回答

是否有任何VB.NET功能或例子来计算字符串或字节数组的CRC32?

Answer 1:

用这个:

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


文章来源: Calculate CRC32 of an String or Byte Array [duplicate]