CRC-8 Counterpart to CRC16() and CRC32()
Posted: 18 June 2010, 11:57 AM
The code below is the 8-bit counterpart to the ZBasic functions CRC16() and CRC32(). It is a general purpose routine that can be used to compute a CRC-8 value for many different CRC-8 algorithms in the same way that the built-in functions can be used. In particular, the parameters for generating a CRC compatible with the Dallas/Maxim 1-wire and with SMBus are given.
Code: Select all
'
'' CRC8
'
' This function is the CRC-8 counterpart to the ZBasic CRC16() and CRC32()
' functions. See the descriptions of those routines for more information about
' the bits of the crcFlags parameter. The Rocksoft model parameters for a
' few popular CRC-8 algorithms are given below.
'
' Name 1-Wire SMBus
' ------- ------ -----
' WIDTH 8 8
' POLY &H31 &H07
' INIT 0 0
' REFIN True False
' REFOUT True False
' XOROUT 0 0
' CHECK &HA1 &HF4
'
Function CRC8(ByRef dataBuf() as Byte, ByVal dataLen as UnsignedInteger, _
ByVal crcPoly as Byte, ByVal crc as Byte, ByVal crcFlags as Byte) as Byte
Dim i as UnsignedInteger
For i = 1 to dataLen
Dim b as Byte
b = dataBuf(i)
If CBool(crcFlags And &H01) Then
' reflected input data
b = FlipBits(b)
End if
Dim mask as Byte
mask = &H80
Do
If CBool(crc And &H80) Xor CBool(b and mask) Then
crc = Shl(crc, 1) Xor crcPoly
Else
crc = Shl(crc, 1)
End If
mask = Shr(mask, 1)
Loop While (mask <> 0)
Next i
' reflected output data
If CBool(crcFlags And &H02) Then
CRC8 = FlipBits(crc)
Else
CRC8 = crc
End If
End Function