因此,遗憾的是,我不得不承认,我放弃了8小时搜索VBA编程语言中正确的CRC8代码。有很多例子,但我还没有找到适用于我的例子。所以我在这里,向你寻求帮助,如果有人能给我写这部分代码,或者如果有一个错误的链接,我还没有点击。
解释:
AppID = "A00000039656434103F0154020D4000A" 在我的项目中,需要在这个AppID的末尾加上char "A“,因为在此基础上应该计算CRC8。如果理解正确(因为我可能在试图编写这个CRC8函数的一整天中疯了),我有32-byte ID,我想对它进行16bits的CRC8检查(这有意义吗?)
在给定的示例中,我只有CRC8应该返回的结果:
CRC8 = 0x6D我需要用主AppID中的字符"A“替换较低的nible:
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!即使我传递entire string或仅传递16bits,也会发生此错误。同样的错误。
如果有人能帮我的忙,我会很感激他的!
发布于 2014-10-31 15:10:12
下面是一个有几个补丁的版本,可以防止溢出的发生。它为十六进制字节(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 Functionhttps://stackoverflow.com/questions/26664204
复制相似问题