校验和根据以下公式计算:
校验和= INV(数据字节1⊕数据字节2⊕...⊕数据字节8)
为了形成校验和,通过模256运算添加各个数据字节。这涉及将溢出位添加到特定中间结果。最后,整体结果是倒置的。 我的尝试(我把这个十六进制数字作为例子,这些数字的正确结果是& H33"):
Private Sub Button46_Click(sender As Object, e As EventArgs) Handles Button46.Click
Dim Sum As Byte = 0
Dim Bytes() As Short = {&H22, &H22, &HAA, &HAA, &H55, &H55, &H44, &H44}
For I As Integer = 0 To Bytes.Length - 1
Sum += Bytes(I) Mod 10
Next
Sum = Not (Sum)
RichTextBox1.Text = Hex(Sum.ToString)
End Sub
向我显示一个溢出异常。我也不知道如何"添加溢出位"有什么想法吗?
答案 0 :(得分:2)
如果要添加它们,需要单独跟踪溢出和模数。这不是你的第一行' Checksum = INV (data byte 1 ⊕ data byte 2 ⊕ ... ⊕ data byte 8)
'虽然 - 但你确定吗?代码就像这样(给&H33
):
Dim sum As Integer = 0
Dim bytes() As Byte = {&H22, &H22, &HAA, &HAA, &H55, &H55, &H44, &H44}
For i As Integer = 0 To bytes.Length - 1
sum += bytes(i)
Next
Dim overflow = sum \ 256
Dim modulo = sum Mod 256
sum = Not (CByte((overflow + modulo) Mod 256))