CRC 冗余校验范例代码,但我还没有读懂,只是记录一下

(1)

在这里插入图片描述
在这里插入图片描述

(2) 代码版:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>  //NULL

struct CCRC32
{
	unsigned int crc32_table[256]; // Lookup table arrays	

	unsigned int Reflect(unsigned int ref, char ch) // 初始化 crc32表 辅助函数	
	{
		unsigned int value(0);

		for (int i = 1; i < (ch + 1); i++) { // Swap bit 0 for bit 7 , bit 1 for bit 6, etc.
			if (ref & 1)	  
				value |= 1 << (ch - i);

			ref >>= 1;
		}
		return value;
	}

	CCRC32() // 这是 CRC-32 在 PKZip、WinZip 和以太网中使用的官方多项式。
	{ // This is the official polynomial used by CRC-32 in PKZip, WinZip and Ethernet.
		unsigned int ulPolynomial = 0x04c11db7;

		for (int i = 0; i <= 0xFF; i++) // 256 values representing ASCII character codes,0xFF = 255 
		{	
			crc32_table[i] = Reflect(i, 8) << 24;

			for (int j = 0; j < 8; j++)
				crc32_table[i] = (crc32_table[i] << 1) ^
				                    (crc32_table[i] & (1 << 31) ? ulPolynomial : 0);

			crc32_table[i] = Reflect(crc32_table[i], 32);
		}
	} 

	int Get_CRC(unsigned char* buffer, unsigned int dwSize)
	{	// 用 crc32_table 寻找表来产生数据的 CRC 值。本函对 地址 buffer 开始的 dwSize 个字节生成检验码。
		// Be sure to use unsigned variables, 一定要使用无符号变量,因为负值引入了需要零位的高位。
		// because negative values introduce high bits where zero bits are required.
		unsigned int  crc(0xffffffff); 	int len = dwSize;

		// Perform the algorithm on each character in the string, using the lookup table values.
		while (len--)
			crc = (crc >> 8) ^ crc32_table[(crc & 0xFF) ^ *buffer++];

		return crc ^ 0xffffffff; // Exclusive OR the result with the beginning value.
	}

};

(3) 以后再学习这个代码。

谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值