CRC16(X16+X15+X2+1) source code

#include  
//x16+x15+x2+1: encode high bit before low bit ..[high bit...low bit] 
unsigned short crc16(unsigned char data, unsigned short crc) {
	unsigned short ccitt16 = 0x8005;
	int i;
	crc ^= (data<<8);
	for (i=0; i<8; i++){
		if (crc & 0x8000){
		   crc <<= 1;
		   crc ^= ccitt16;
		}
		else{
		   crc <<= 1;
		}
	}
	return crc;
}
//x16+x15+x2+1: encode high bit after low bit ..[low bit...high bit]. 
unsigned short crc16_r(unsigned char data, unsigned short crc){
	unsigned short ccitt16 = 0xa001;    //(0x8005->[reverse]->0xa001)
	int i;
	crc ^= data;
	for (i=0; i<8; i++){
		if (crc & 1){
		   crc >>= 1;
		   crc ^= ccitt16;
		}
		else{
		   crc >>= 1;
		}
	}
	return crc;
}

unsigned short calculate_crc16(unsigned char* buf, int len, unsigned short crc){
    unsigned short crc16_table[256];
	for(unsigned int i=0; i<256; i++){
		crc16_table[i] = crc16(i, 0);
	}
	for(unsigned int i=0; i<len; i++){
		crc = crc16_table[((crc>>8)^buf[i])&0xff]^(crc<<8);	
	}
	return crc;
}

unsigned short calculate_crc16_r(unsigned char* buf, int len, unsigned short crc){
    unsigned short crc16_table_r[256];
	for(unsigned int i=0; i<256; i++){
		crc16_table_r[i] = crc16_r(i, 0);
	}
	for(unsigned int i=0; i<len; i++){
		crc = crc16_table_r[((crc)^buf[i])&0xff]^(crc>>8);	
	}
	return crc;
}

int main()
{
	unsigned short crc = 0;
	unsigned char buf[] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10};
	int len = sizeof(buf)/sizeof(unsigned char);
	//CRC-16:init_crc=0x0, result ^= 0, in/out_put_data(no reverse)
	crc = calculate_crc16(buf, len, 0);
	printf("crc16 = 0x%x\n", crc);
	//CRC-16/IBM:init_crc=0x0, result ^= 0, in/out_put_data(reverse)
	crc = calculate_crc16_r(buf, len, 0);
	printf("crc16_r = 0x%x\n", crc);
    return 0;
}

Useful Reference link

你可能感兴趣的:(算法)