crc校验完整实验c语言实现
时间: 2023-08-25 20:07:34 浏览: 116
下面是一个简单的CRC校验的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CRC8_POLYNOMIAL 0x07
#define CRC16_POLYNOMIAL 0x1021
#define CRC32_POLYNOMIAL 0xEDB88320
unsigned char crc8(unsigned char *data, int len)
{
unsigned char crc = 0;
int i, j;
for (i = 0; i < len; i++) {
crc ^= data[i];
for (j = 0; j < 8; j++) {
if (crc & 0x80) {
crc = (crc << 1) ^ CRC8_POLYNOMIAL;
} else {
crc <<= 1;
}
}
}
return crc;
}
unsigned short crc16(unsigned char *data, int len)
{
unsigned short crc = 0;
int i, j;
for (i = 0; i < len; i++) {
crc ^= (data[i] << 8);
for (j = 0; j < 8; j++) {
if (crc & 0x8000) {
crc = (crc << 1) ^ CRC16_POLYNOMIAL;
} else {
crc <<= 1;
}
}
}
return crc;
}
unsigned int crc32(unsigned char *data, int len)
{
unsigned int crc = 0xFFFFFFFF;
int i, j;
for (i = 0; i < len; i++) {
crc ^= data[i];
for (j = 0; j < 8; j++) {
if (crc & 0x80000000) {
crc = (crc << 1) ^ CRC32_POLYNOMIAL;
} else {
crc <<= 1;
}
}
}
return ~crc;
}
int main()
{
unsigned char data[] = "hello world";
unsigned char crc8_val = crc8(data, strlen(data));
unsigned short crc16_val = crc16(data, strlen(data));
unsigned int crc32_val = crc32(data, strlen(data));
printf("CRC8: 0x%x\n", crc8_val);
printf("CRC16: 0x%x\n", crc16_val);
printf("CRC32: 0x%x\n", crc32_val);
return 0;
}
```
在该代码中,我们定义了三个CRC多项式,分别为8位、16位和32位的CRC校验。然后我们编写了三个函数,分别实现了对应多项式的校验算法。其中,CRC8算法使用了一个8位的查找表,CRC16算法使用了一个16位的查找表,而CRC32算法则直接按照多项式计算。最后在主函数中,我们对字符串"hello world"分别进行了三种CRC校验,并输出了校验结果。
阅读全文