计算字符串或字节数组的CRC32值

4
在VB.NET中,是否有计算字符串或字节数组的CRC32的函数或示例?

1
这是你需要的吗?(链接指向stackoverflow上一个关于如何计算字符串CRC32值的问题) - Rajaprabhu Aravindasamy
其实我之前查看了一些相关内容,但是它们都不起作用,大部分链接都是关于计算文件CRC32的。 - Shahriyar
1
"没有一个能够工作。到底出了什么问题?" - Magnus
1个回答

15

使用此代码:

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

帮了很多忙...好问题和优秀的答案....两个都加一.. - Venu GoPal
@Magnus...如果我使用Encoding.UTF7Encoding.UTF32代替Encoding.UTF8,有什么区别? - Venu GoPal
1
@VenuGoPal 你可以在这里找到有关此问题的有用信息:https://javarevisited.blogspot.com/2015/02/difference-between-utf-8-utf-16-and-utf.html#axzz6dTQdmFYI,但本质上它是表示一个字符所需的位数。不同的编码方式会以不同的方式实现这一点。 - Magnus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接