Code for calculating CRC32

Here is the code to calculate the CRC32 for as used by Sinocastel.
This code was tested in Visual Studio 2013. Just create a new console application and copy the following.

Imports System.Text

Module Module1

    Sub Main()

        Dim btarray As Byte()
        btarray = {&H40, &H40, &H1E, &H0, &H0, &H0, &H0, _
                   &H0, &H0, &H0, &H0, &H0, &H0, &H0, _
                   &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H0, &H12, &HE}

        Console.WriteLine(Hex(Crc32.ComputeChecksum(btarray)))

        Do While True 'Wait forever
        Loop

    End Sub
    Public Class Crc32
        Shared table As UInteger()

        Shared Sub New()
            Dim poly As UInteger = &H8408UI 'Starting polynomial used by Sinocastel 
            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(ByVal bytes As Byte()) As UInteger
            Dim crc As UShort = &HFFFFUI 'Initial value of CRC
            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

End Module

No comments:

Post a Comment