计算CRC 16 white POLYNOMIAL 0x8408和initial crc 0xFFFF

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

您好,我需要使用多项式 0x8408 和初始值 0xFFFF 获取 CRC16,在此 post 我发现了一个相同的情况

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

但我在 VB 2013 年工作,我打算用这种语言编写相同的代码

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

但是当我执行这段代码时,在 crc = CUShort(crc ^ pru(j))

中出现溢出

有什么可以帮助我的。

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

谢谢,代码有效

在 C# 中,^ operator 是异或。在VB中,^运算符是求幂。

只需将每个 ^ 更改为 Xor