我在使用Excel VBA进行CRC8计算时分手了。我在VBA中编写了一个函数,它返回CRC8值,以后可以存储到单元格中。然而,在打印时,我得到错误说" OverFlow"。
我在" ShiftLeft = Num *(2 ^ Places)"
的函数中溢出Function CRCPrateek(CRCrng As Range) As Integer
Dim CRC As Integer
Dim length As Integer
Dim Hexbyte As Integer
Dim i As Integer
'Initial CRC seed is Zero CRC = H00
'The real part of the CRC. Where I commented "Polynomial", it used to be a # define
'Polynomial 7. 'I replaced the word Polynomial with 7, however that means the 7 may
'be subject to change depending on the version of the crc you are running.
'To loop it for each cell in the range
For Each cel In CRCrng
'Verify if there is atleast one cell to work on
If Len(cel) > 0 Then
Hexbyte = cel.Value
CRC = CRC Xor Hexbyte
For i = 0 To 7
If Not CRC And H80 Then
CRC = ShiftLeft(CRC, 1)
CRC = CRC Xor 7
Else
CRC = ShiftLeft(CRC, 1)
End If
Next
End If
Next
CRCPrateek = CRC
End Function
Function ShiftLeft(Num As Integer, Places As Integer) As Integer
ShiftLeft = Num * (2 ^ Places)
End Function
答案 0 :(得分:0)
您正在处理2字节整数,而不是字节。此外,我怀疑cell.value确实是一个十六进制值 - 而不是一个十六进制字符串,如' 3F'您必须先将其转换为数值(在0..255范围内) 为了创建真正的字节数组,字节CRC赋予此解决方案:Calculating CRC8 in VBA
在那里你会找到溢出的解决方案,即在移位之前屏蔽最高位。
答案 1 :(得分:0)
其他'努力与建议帮助我找到了正确的答案;我发布了我写的通用函数来计算CRC8。它给了我想要的结果&我还检查了其他CRC计算器。
'GENERATE THE CRC
Function CRCPrateek(ByVal crcrng As Range) As Long
Dim crc As Byte
Dim length As Byte
Dim Hexbyte As String
Dim DecByte As Byte
Dim i As Byte
' Initial CRC seed is Zero
crc = &H0
'The real part of the CRC. Where I commented "Polynomial", it used to be a # define
'Polynomial 7. I replaced the word Polynomial with 7, however that means the 7 may
'be subject to change depending on the version of the crc you are running.
'To loop it for each cell in the range
For Each cel In crcrng
'Verify if there is atleast one cell to work on
' If Len(cel) > 0 Then
DecByte = cel.Value
crc = crc Xor DecByte
For i = 0 To 7
If ((crc And &H80) <> 0) Then
crc = ShiftLeft(crc, 1)
crc = crc Xor 7
Else
crc = ShiftLeft(crc, 1)
End If
Next
' End If
Next
CRCPrateek = crc
End Function
Function ShiftLeft(ByVal Num As Byte, ByVal Places As Byte) As Byte
ShiftLeft = ((Num * (2 ^ Places)) And &HFF)
End Function
'END OF CRC
在调用上述函数时,你唯一要作为参数传递的是单元格的范围(具有小数(在单元格中使用HEX2DEC)值。
'EXAMPLE CALL TO CRC FUNCTION FROM A SUB
'select the crc Range
Set crcrng = Range("I88", "U88")
crc = CRCPrateek(crcrng)
Sheet1.Cells(88, 22).Value = crc
MsgBox ("CRC value is " & Sheet1.Cells(86, 22).Value & "(in HEX) ")
注意:此函数将输入值作为小数,以十进制和&amp;计算CRC值。稍后在返回CRC值后,您可以将其存储在任何其他单元格中。通过在单元格中使用公式DEC2HEX将其转换回十六进制