Search code examples
vb.netcrc16

Calcule the CRC16 whit POLYNOMIAL 0x8408 and initial crc 0xFFFF


Hi I need get the CRC16 with polynomial 0x8408 and initial 0xFFFF, in this post I found a equal case

C# CRC-16-CCITT 0x8408 Polynomial. Help needed

but I am working in VB 2013 and I intend write the same code but in this language

Private Sub crc16calc_Click(sender As Object, e As EventArgs) Handles crc16calc.Click

        Dim data As UShort = 0
        Dim crc As UShort = &HFFFF
        Dim pru() As Byte = {&H5, &H0, &H4, &HFB, &H4A, &H43}

        For j As UInteger = 0 To pru.Length - 1
            crc = CUShort(crc ^ pru(j))
            For i As UInteger = 0 To 7
                If ((crc & &H1) = 1) Then
                    crc = CUShort((crc >> 1) ^ &H8408)
                Else
                    crc >>= 1
                End If

            Next

        Next


        crc = CUShort(Not crc)
        data = crc
        crc = CUShort((crc << 8) ^ (data >> 8 & &HFF))

        MsgBox(crc)

    End Sub

But when I execute this code get a overflow in crc = CUShort(crc ^ pru(j))

Can any help me.

Private Sub crc16calc_Click(sender As Object, e As EventArgs) Handles crc16calc.Click

    Dim data As UShort
    Dim PRESET_VALUE As UShort = &HFFFF
    Dim POLYNOMIAL As UShort = &H8408
    Dim pru() As Byte = {&H4, &H0, &H1, &HDB, &H4B} ' the two last bytes are the CRC16
    Dim pru2() As Byte = {&H5, &H0, &H1, &HFB, &HF2, &H3D}
    Dim ucX As Integer = pru.Length - 3

    Dim uiCrcValue As UShort = PRESET_VALUE

    For j As Integer = 0 To ucX

        uiCrcValue = uiCrcValue Xor pru(j)

        For i As Integer = 0 To 7

            If (uiCrcValue And 1) Then
                uiCrcValue = (uiCrcValue >> 1) Xor POLYNOMIAL
            Else
                uiCrcValue = uiCrcValue >> 1
            End If

        Next

    Next

    'MsgBox(uiCrcValue)
    data = uiCrcValue
    uiCrcValue = CUShort((uiCrcValue << 8) Xor ((data >> 8) And &HFF))
    MsgBox(uiCrcValue)

End Sub

Thanks, the code is working


Solution

  • In C# the ^ operator is xor. In VB, the ^ operator is exponentiation.

    Just change each ^ to Xor.