CRC(循环冗余校验)程序可以通过多种编程语言实现,包括C语言、Python等。下面我将提供几个不同CRC算法的C语言实现示例。
CRC-4 实现
```c
include
uint8_t crc4_D(uint8_t data) {
uint8_t crc = 0;
uint8_t poly = 0x09;
int i;
poly = poly << 4;
crc = data;
for (i = 0; i < 8; i++) {
if (crc & 0x80)
crc = (crc << 1) ^ poly;
else
crc = crc << 1;
}
return crc;
}
```
CRC-32 实现
```c
include
uint32_t cfgCrc32(const unsigned char *pSrc, int nSize) {
int i, j, nIdx = 0;
unsigned int byte, crc, mask;
static unsigned int table;
if (table == 0) {
for (byte = 0; byte < 256; byte++) {
mask = -(byte & 1);
crc = (crc >> 1) ^ (0xEDB88320 & mask);
table[byte] = crc;
}
}
crc = 0xFFFFFFFF;
for (; nIdx < nSize; nIdx++) {
crc ^= pSrc[nIdx];
for (i = 0; i < 8; i++) {
if (crc & 0x80000000)
crc = (crc << 1) ^ 0xEDB88320;
else
crc <<= 1;
}
}
return ~crc;
}
```
CRC-16 实现
```c
include
uint16_t crc16(uint16_t data, uint16_t polynomial) {
uint16_t crc = 0xFFFF;
for (int i = 0; i < 16; i++) {
if (crc & 0x8000) {
crc = (crc << 1) ^ polynomial;
} else {
crc <<= 1;
}
crc &= 0xFFFF;
}
crc ^= data;
return crc;
}
```
使用示例
```c
include
int main() {
uint8_t data = 0xB3;
uint8_t crc = crc4_D(data);
printf("CRC-4 of %02X is %02X\n", data, crc);
uint32_t data32 = 0x12345678;
uint32_t crc32 = cfgCrc32((unsigned char*)&data32, sizeof(data32));
printf("CRC-32 of %08X is %08X\n", data32, crc32);
uint16_t data16 = 0xABCD;
uint16_t crc16 = crc16(data16, 0x1021);
printf("CRC-16 of %04X is %04X\n", data16, crc16);
return 0;
}
```
这些示例展示了如何实现和计算不同数据长度的CRC值。你可以根据需要选择合适的CRC算法和参数。