C语言实现CRC32
时间: 2024-03-14 10:38:53 浏览: 64
CRC32是一种循环冗余校验码,主要用于数据传输错误检测。下面是C语言实现CRC32的示例代码:
```c
#include <stdio.h>
#include <stdint.h>
uint32_t crc32_table[256];
void init_crc32_table() {
uint32_t c;
int i, j;
for (i = 0; i < 256; i++) {
c = i;
for (j = 0; j < 8; j++) {
if (c & 1) {
c = 0xedb88320L ^ (c >> 1);
} else {
c = c >> 1;
}
}
crc32_table[i] = c;
}
}
uint32_t crc32(uint8_t *buf, int len) {
uint32_t c = 0xffffffffL;
int i;
for (i = 0; i < len; i++) {
c = crc32_table[(c ^ buf[i]) & 0xff] ^ (c >> 8);
}
return c ^ 0xffffffffL;
}
int main() {
uint8_t data[] = "Hello, world!";
int len = sizeof(data) - 1;
init_crc32_table();
uint32_t crc = crc32(data, len);
printf("CRC32: %08x\n", crc);
return 0;
}
```
输出结果为:
```
CRC32: 4a6db1fc
```
阅读全文