Code

CRC calculation

Emmanuel February 15, 2011 Coded in C

This code contains a function which calculates the checksum based on the 8-bit  CRC algorithm for  x^7+x+1 as the generator polynomial which can be changed for any other polynomial.

Its input values are the data and its length. Its output is the 8 bit word obtained from the CRC operation.

This code is portable to any platform which use a C compilator as it works whit 8 bits words and simple operations as shifting registers.

 

unsigned char crc(unsigned char data[],int L)
{
	
    unsigned char P=0x83;
    unsigned char *data_ptr;
	unsigned char crc_result;
	int bit;
	crc_result=0;
	for(data_ptr=data;data_ptr<data+L;data_ptr++)
	{
		for(bit=7;bit>=0;bit--)
		{
            crc_result=(crc_result<<1)+((*data_ptr&0x1<<bit)>>bit);
			if (crc_result>=128)
			{
				crc_result=crc_result^P;
			}
		}
	}
	//multiply by 2^n-k;
	for(bit=6;bit>=0;bit--)
		{
            crc_result=(crc_result<<1);
			if (crc_result>=128)
			{
				crc_result=crc_result^P;
			}
		}

	return crc_result;
		
}