Ok, I think this should be ok now!
I added a parameter to the function which is optional,
=CITT_CRC_HEX(B2,TRUE)
Will reverse the order of the bytes
=CITT_CRC_HEX(B2,FALSE)
=CITT_CRC_HEX(B2)
Are the same!
Function Rand_Hex(NumBytes As Integer) As String
Application.Volatile
For J = 1 To NumBytes
Rand_Hex = Rand_Hex & Right("00" & Hex(Int(Rnd(1) * 256)), 2)
Next J
End Function
Function CITT_CRC_HEX(myString As String, Optional reverse As Boolean = False) As String
Dim temp() As Byte
ReDim temp(Len(myString) / 2 - 1)
For J = 1 To Len(myString) Step 2
temp((J - 1) / 2) = Val("&h" & Mid(myString, J, 2))
Next J
CITT_CRC_HEX = CRC16_4(temp(), reverse)
End Function
Function CITT_CRC_String(myString As String, Optional reverse As Boolean = False) As String
Dim temp() As Byte
ReDim temp(Len(myString) - 1)
For J = 1 To Len(myString)
temp(J - 1) = Asc(Mid(myString, J, 1))
Next J
CITT_CRC_HEX = CRC16_4(temp(), reverse)
End Function
Private Function CRC16_4(Buffer() As Byte, reverse As Boolean) As String
Const CRC_POLYNOM As Long = &H8408&
Const CRC_PRESET As Long = &HFFFF&
Dim CRC As Long, I As Long, J As Long
CRC = CRC_PRESET 'unsigned internal CRC = CRC_PRESET
For I = 0 To UBound(Buffer) 'for(i=0; i < cnt; i++)
CRC = CRC Xor Buffer(I) 'crc ^= Buffer[i]
For J = 0 To 7 'for(j=0; j<8;j++)
If (CRC And 1) Then 'if(crc & 0x0001)
CRC = (CRC \ 2) Xor CRC_POLYNOM 'crc=(crc>>1)^CRC_POLYNOM;
Else
CRC = (CRC \ 2) 'crc=(crc>>1)
End If
Next J
Next I
CRC16_4 = Right("0000" & Hex$((Not CRC) And &HFFFF&), 4)
If reverse = False Then
CRC16_4 = Right(CRC16_4, 2) & Left(CRC16_4, 2)
End If
End Function
If you'd rather that the results where the other way round (I got confused which one you wanted along the way)
Change the line
to
at the bottom of the code!
Bookmarks