6.a. CRC Computation in C

The following example program shows how to compute a CRC in the C language. The idea is that the CRC of every possible byte is stored in a lookup table, so that it can be quickly loaded when computing the CRC of a longer message. The individual CRC bytes are XORed together with the C operator ^ to get the final CRC of the message. In the example main() routine, this is applied to generate the CRC byte in the message 0x83, 0x01, that was used in Section 6.

#include <stdio.h>

const unsigned char CRC7_POLY				= 0x91;
unsigned char CRCTable[256];

unsigned char GetCRC(unsigned char val)
{
	unsigned char j;

	for (j = 0; j < 8; j++)
	{
		if (val & 1)
			val ^= CRC7_POLY;
		val >>= 1;
	}

	return val;
}

void GenerateCRCTable()
{
    int i, j;

    // generate a table value for all 256 possible byte values
    for (i = 0; i < 256; i++)
    {
        CRCTable[i] = GetCRC(i);
    }
}

unsigned char CRC(unsigned char message[], unsigned char length)
{
	unsigned char i, crc = 0;

	for (i = 0; i < length; i++)
		crc = CRCTable[crc ^ message[i]];
	return crc;
}

int main()
{
	unsigned char message[3] = {0x83, 0x01, 0x00};
	int i,j;

	GenerateCRCTable();
	message[2] = CRC(message,2);

	for(i=0;i<sizeof(message);i++)
	{
		for(j=0;j<8;j++)
			printf("%d",(message[i]>>j)%2);
		printf(" ");
	}
	printf("\n");
	return 0;
}

Related Products

Pololu Qik 2s9v1 Dual Serial Motor Controller
Log In
Pololu Robotics & Electronics
Shopping cart
(702) 262-6648
Same-day shipping, worldwide
Menu
Shop Blog Forum Support
My account Comments or questions? About Pololu Contact Ordering information Distributors