CRC-32(x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1) source code

#include <stdio.h> 
//x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1
//encode high bit before low bit ..[high bit...low bit]
unsigned int crc32(unsigned char data, unsigned int crc) {
	unsigned int crc32 = 0x04C11DB7;
	int i;
	crc ^= (data<<24);
	for (i=0; i<8; i++){
		if (crc & 0x80000000){
		   crc <<= 1;
		   crc ^= crc32;
		}
		else{
		   crc <<= 1;
		}
	}
	return crc;
}

//x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x+1
//encode low bit before high bit ..[low bit...hig bit]
unsigned int crc32_r(unsigned char data, unsigned int crc){
	unsigned int crc32_r = 0xEDB88320; 	//(0x04C11DB7->[reverse]->0xEDB88320)
	int i;
	crc ^= data;
	for (i=0; i<8; i++){
		if (crc & 1){
		   crc >>= 1;
		   crc ^= crc32_r;
		}
		else{
		   crc >>= 1;
		}
	}
	return crc;
}

unsigned int calculate_crc32(unsigned char* buf, int len, unsigned int crc){
    unsigned int crc32_table[256];
	for(unsigned int i=0; i<256; i++){
		crc32_table[i] = crc32(i, 0x0);
	}
	for(unsigned int i=0; i<len; i++){
		crc = crc32_table[((crc>>24)^buf[i])&0xff]^(crc<<8);	
	}
	return crc;
}

unsigned int calculate_crc32_r(unsigned char* buf, int len, unsigned int crc){
    unsigned int crc32_table_r[256];
	for(unsigned int i=0; i<256; i++){
		crc32_table_r[i] = crc32_r(i, 0x0);
	}
	for(unsigned int i=0; i<len; i++){
		crc = crc32_table_r[((crc)^buf[i])&0xff]^(crc>>8);	
	}
	return crc ^ (~0U);
}

int main()
{
	unsigned char buf[] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0x10,0x20};
	int len = sizeof(buf)/sizeof(unsigned char);

	unsigned int crc32;
	//CRC-32/MPEG-2, init_crc=~0U, result ^= 0U, in/out_put_data(no reverse)
	crc32 = calculate_crc32(buf, len, 0xffffffff); 
	printf("crc32 = 0x%x\n", crc32);
	//CRC-32, init_crc=~0U, result ^= ~0U, in/out_put_data(reverse)
	crc32 = calculate_crc32_r(buf, len, 0xffffffff);
	printf("crc32_r = 0x%x\n", crc32);
	
	return 0;
}

Useful Reference link

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值