写一个CRC校验的c语言程序
时间: 2024-05-14 16:14:50 浏览: 8
下面是一个简单的CRC校验的c语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#define WIDTH (8 * sizeof(uint32_t))
#define TOPBIT (1 << (WIDTH - 1))
#define POLYNOMIAL 0x04C11DB7
uint32_t crc32(uint32_t remainder, unsigned char *message, size_t nBytes) {
uint32_t byte, mask;
for (size_t i = 0; i < nBytes; i++) {
byte = message[i];
remainder ^= (byte << (WIDTH - 8));
for (uint8_t bit = 8; bit > 0; bit--) {
if (remainder & TOPBIT) {
remainder = (remainder << 1) ^ POLYNOMIAL;
} else {
remainder = (remainder << 1);
}
}
}
return remainder;
}
int main(void) {
unsigned char message[] = "123456789";
size_t nBytes = sizeof(message) - 1;
uint32_t remainder = crc32(0, message, nBytes);
printf("CRC-32: 0x%" PRIx32 "\n", remainder);
return 0;
}
```
这是一个简单的CRC校验代码,它通过对一个字符串的每一个字节进行校验,并对校验结果进行计算。这个代码使用了32位的CRC校验算法。你可以根据自己的需要调整代码。