【发布时间】:2011-01-27 03:53:43
【问题描述】:
好的,这段代码可以工作,但我认为它在中间有一些必要的步骤来获得结果。关于如何使它更紧的任何想法?
Public Function CalCheckSum(ByVal ByteList As List(Of Byte)) As List(Of Byte)
Dim total As Integer = 0
For Each b As Byte In ByteList
total = total + b
Next
Dim modedVal As Integer = 0
modedVal = total Mod &H100
Dim negatedValue As Integer = 0
negatedValue = &H100 - modedVal
Dim charList As List(Of Char) = Hex(negatedValue).ToCharArray.ToList
Dim returnList As New List(Of Byte)
For Each ch As Char In charList
returnList.Add(Asc(ch))
Next
Return returnList
End Function
顺便说一句,这是我用来测试的:
Dim blist As New List(Of Byte)
blist.Add(&H52)
blist.Add(&H34)
blist.Add(&H35)
blist.Add(&H31)
blist.Add(&H32)
blist.Add(&H33)
blist.Add(&H34)
blist.Add(&H30)
blist.Add(&H30)
blist.Add(&H30)
blist.Add(&H30)
blist.Add(&H46)
blist.Add(&H46)
blist.Add(&H46)
blist.Add(&H46)
blist.Add(&H42)
blist.Add(&H4B)
blist.Add(&H9)
blist.Add(&H44)
Dim b As List(Of Byte) = CalCheckSum(blist)
b 的正确值为:
-
b(0)= &H43 -
b(1)= &H39
【问题讨论】:
-
我对校验和算法了解不多,但
&H100看起来很奇怪。你确定不想要&HFF? -
您是否有特殊原因要重新发明自己的校验和算法,而不是使用 .NET Framework 在
System.Security.Cryptographynamespace 中已经提供的算法之一?例如,MD5 哈希通常是一个完美可行的解决方案。 -
Cody Gray:我没有发明自己的校验和算法。以上是与已经使用该算法的嵌入式硬件设备进行通信。我只是在 vb.net 中编写它,这样我就可以与该设备进行通信。正如我所说,上面的代码可以与设备通信......只是代码看起来很乱。
-
嗨 Chris - 是的 &H100(或 256 十进制)显然是正确的。从原始校验和文档中:总结所有字段并计算 mod 0x100。然后将其取反以得到两个字节的校验和。校验和值转换为两个十六进制数字并插入到消息中
标签: vb.net algorithm performance optimization checksum