首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >计算字符串或字节数组的CRC16的VB.NET示例

计算字符串或字节数组的CRC16的VB.NET示例
EN

Stack Overflow用户
提问于 2014-04-11 17:44:17
回答 2查看 11.4K关注 0票数 1

参考这个链接Calculate CRC32 of an String or Byte Array我修改了代码来计算CRC16而不是CRC32,但是我得到了错误的结果,有人能告诉我错误在哪里吗?

代码语言:javascript
运行
复制
Private Sub Main()
Crc16.ComputeChecksum(Encoding.UTF8.GetBytes("Some string"))
End Sub
    Public Class CRC16
Shared table As UShort()

Shared Sub New()
    Dim poly As UShort = &HA001US 'calculates CRC-16 using A001 polynomial (modbus)
    table = New UShort(255) {}
    Dim temp As UShort = 0
    For i As UShort = 0 To table.Length - 1
        temp = i
        For j As Integer = 8 To 1 Step -1
            If (temp And 1) = 1 Then
                temp = CUShort((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 UShort
    Dim crc As UShort = &H0US ' The calculation start with 0x00
    For i As Integer = 0 To bytes.Length - 1
        Dim index As Byte = CByte(((crc) And &HFF) Xor bytes(i))
        crc = CUShort((crc >> 8) Xor table(index))
    Next
    Return Not crc
End Function
End Class
EN

回答 2

Stack Overflow用户

发布于 2014-10-28 21:30:17

试试这个,它是用于仪器控制的VB6代码。(sCommand是一个包含所有字节的临时字符串,结果被添加到sCommand中,Modbus首先使用LSB,TextToString和StringToAscii是用于将可读字符串"FF EE“转换为ASCII码并将其转换回来的函数,因此这里对它们不感兴趣):

代码语言:javascript
运行
复制
Private Sub cmdCRC16_Click()
Dim sCommand As String
Dim x As Long
Dim y As Long
Dim lCRC As Long
sCommand = TextToString(txtASCII)
'Initial value
lCRC = 65535 '(&HFFFF results in Integer -1)
For x = 1 To Len(sCommand)
    lCRC = lCRC Xor Asc(Mid(sCommand, x, 1))
    For y = 1 To 8
        If (lCRC Mod 2) > 0 Then
            lCRC = (lCRC And 65534) / 2
            lCRC = lCRC Xor 40961 '(&HA001 results in whatever negative integer)
        Else
            lCRC = (lCRC And 65534) / 2
        End If
    Next y
Next x
'Add CRC with LSB first
sCommand = sCommand + Chr(lCRC And 255)
sCommand = sCommand + Chr((lCRC And 65280) / 256)
txtASCII = StringToASCII(sCommand)

结束子对象

票数 1
EN

Stack Overflow用户

发布于 2017-02-25 04:56:48

我也遇到了同样的问题。简单的解决方案是省略结尾的否定,所以只需将"Return Not crc“更改为"Return crc”,就可以了。

CRC-16有多种变体,其中"CRC-16“不是指IBM变体,也称为"ARC”。它使用的XorOut值为零。参见Catalogue of parametrised CRC algorithms with 16 bits

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23009036

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档