26
CVS4 Component Video Switch
27
CVS4 Component Video Switch
Source Code Example of Calculating a CRC-8 Checkcode
The following is a simple “C” program that calculates the CRC-8 of the string “TestString” and
then prints the initial string with the calculated CRC-8 checkcode appended to it.
#include "stdio.h"
// Routine for updating the CRC-8 checkcode using a polynomial
// of: x^8 +x^6 +x^3 +x^2 + 1.
//
// To create the CRC8_POLY mask, we start by ignoring the highest
// bit (x^8) since it is assumed to always be 1 and lies outside
// our byte boundary, and doesn't affect our results.
//
// The rest of the bits of the polynomial are reversed from the
// polynomial's order. This allows us to read in each bit starting
// with bit 0 of each byte, instead of bit 7. This is done because
// the UART sends its LSB first and by doing the same we are able to
// preserve the CRC's burst error detection characteristics.
//
// So:
// x^8 +x^6 +x^3 +x^2 + 1 = 101001101 = 14D hex
// Ignore X^8: 01001101 = 4D hex
// Reverse bit order: 10110010 = B2 hex
#define CRC8_POLY 0xB2
// polynomial mask
#define CRC8_INIT 0xFF
// initial value
void crcByte( unsigned char *crc8, char cc)
{
unsigned char lcrc8;
// local copy of CRC-8 value
int
bitcount;
lcrc8 = *crc8;
// get local copy of CRC-8
// update CRC-8 with 8 new bits
lcrc8 ^= cc;
// test each bit against CRC-8
for (bitcount = 0; bitcount < 8; b+)
{
// if resultant bit was a 1, shift and xor in mask
// else, just shift
if (lcrc8 & 0x01)
lcrc8 = ((lcrc8 >> 1) & 0x7F) ^ CRC8_POLY;
else
lcrc8 = (lcrc8 >> 1) & 0x7F;
}
*crc8 = lcrc8;
// return new CRC8
}
int main( void)
{
char
TestString[] = "LI 2,3";
unsigned char crc8;
int
index;
char
token = ':';
crc8 = CRC8_INIT;
// initialize checkcode
// CRC8 all of TestString[]
index = 0;
while (TestString[index] != 0)
crcByte( &crc8, TestString[index++]);
// Add the CRC-8 token character ':' to CRC-8
crcByte( &crc8, token);
// Finish with CRC8 by doing a one's compliment
crc8 = ~crc8;
// Print the results
printf( "%s%c%u", TestString, token, (unsigned char)crc8);
return (0);
}
Checksums and CRC-8’s
(Cont’d)
Checksums and CRC-8’s
(Cont’d)