gpt4 book ai didi

ms-access - 在 VBA 中计算 CRC8

转载 作者:行者123 更新时间:2023-12-03 20:35:08 25 4
gpt4 key购买 nike

很遗憾,我不得不承认我放弃了用 VBA 编程语言搜索正确的 CRC8 代码的 8 小时。有很多例子,但我还没有找到适合我的例子。所以我在这里,向您寻求帮助,是否有人可以将这部分代码写给我,或者是否有一个我没有点击过的神秘链接。

解释:

AppID = "A00000039656434103F0154020D4000A" 

在我的项目中,要求字符“A”位于此 AppID 的末尾,因为应基于此计算 CRC8。如果理解正确(因为我可能一整天都在尝试编写此 CRC8 函数而发疯)我有 32-byte ID,我想在 16bits 上对其进行 CRC8 检查(这有意义吗?)

在给定的示例中,我只有 CRC8 应该返回的结果:

CRC8 = 0x6D

我需要用我的主 AppID 中的字符“A”替换下半部分:

FinalAppID = "A00000039656434103F0154020D4000D"

问题:但我根本不知道如何编写或转换 C++/C# 代码。我真的被逐步转换所困扰,但它没有用。

这是我使用的代码:

Public function calculateCRC8(ByVal AppID As String ) As String
Dim CRC8 As Byte
Dim i as Integer
Dim j as Integer
Dim AppIDarray()


CRC8 = &HC7; //Based on preset 0xE3 
    aidLenght = LEN(AppID)
AppIDarray = StringToArray(AppID) ' I user a UDF that I wrote, this should work OK'
For j = 0 To aidLenght
                CRC8 = CRC8 Xor AppIDarray(j) 
           For i = 1 To 8
If CRC8 And &H80 Then
CRC8 = (CRC8 * 2) Xor &H1D
Else
CRC8 = CRC8 * 2
End If
next i
Next j
calculateCRC8 = CRC8
End Function

以上代码出现的问题是:

错误:

Error: Overflow!

即使我传递了整个字符串,或者只是16bits,也会出现这个错误。同样的错误。

如果有人有什么可以帮助我的,我将非常感谢他!

最佳答案

这是一个带有一些修复的版本,它可以防止溢出的发生。它为您的十六进制字节 (A00000039656434103F0154020D4000A) 生成预期结果 (&H6D)。

Public Function calculateCRC8(ByVal AppID As String) As String
Dim CRC8 As Byte
Dim i As Integer
Dim j As Integer
Dim AppIDarray() As Byte '<--- explicitly dimensioned as a Byte array to avoid confusion


CRC8 = &HC7

'The AppID is actually bytes stored in hexadecimal in a string. You have to convert them back to bytes before you can run a crc8 on them.
AppIDarray = HexToByte(AppID)
aidLength = UBound(AppIDarray)
For j = 0 To aidLength
CRC8 = CRC8 Xor AppIDarray(j)
For i = 1 To 8
If CRC8 And &H80 Then
'masking off the left-most bit before shifting prevents the Overflow error.
CRC8 = ((&H7F And CRC8) * 2) Xor &H1D
Else
CRC8 = CRC8 * 2
End If
Next i
Next j
calculateCRC8 = CRC8
End Function

此函数接受十六进制字符串并将其解释为 Byte 数组。

Public Function HexToByte(strHex As String) As Byte()
Dim i As Integer
Dim tempByte As Byte
Dim outBytes() As Byte
ReDim outBytes(Len(strHex) \ 2 - 1)
For i = 0 To Len(strHex) \ 2 - 1
For j = 0 To 1
char = Mid(strHex, i * 2 + j + 1, 1)
Select Case char
Case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
tempByte = tempByte Or (Asc(char) - 48)
Case "A", "B", "C", "D", "E", "F":
tempByte = tempByte Or (Asc(char) - 55)
End Select
If j = 0 Then
tempByte = tempByte * 2 ^ 4
Else
outBytes(i) = tempByte
tempByte = 0
End If
Next
Next
HexToByte = outBytes
End Function

关于ms-access - 在 VBA 中计算 CRC8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26664204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com