C++ 分别实现CRC8,CRC16,CRC32校验数据
时间: 2023-07-31 21:12:23 浏览: 545
以下是C++实现CRC8、CRC16、CRC32校验数据的示例代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
// CRC8校验
uint8_t calc_crc8(uint8_t *data, uint32_t len)
{
uint8_t crc = 0x00;
uint8_t gen_poly = 0x07;
for (uint32_t i = 0; i < len; i++)
{
crc ^= data[i];
for (uint8_t j = 0; j < 8; j++)
{
if (crc & 0x80)
crc = (crc << 1) ^ gen_poly;
else
crc <<= 1;
}
}
return crc;
}
// CRC16校验
uint16_t calc_crc16(uint8_t *data, uint32_t len)
{
uint16_t crc = 0xFFFF;
uint16_t gen_poly = 0x1021;
for (uint32_t i = 0; i < len; i++)
{
crc ^= (uint16_t)data[i] << 8;
for (uint8_t j = 0; j < 8; j++)
{
if (crc & 0x8000)
crc = (crc << 1) ^ gen_poly;
else
crc <<= 1;
}
}
return crc;
}
// CRC32校验
uint32_t calc_crc32(uint8_t *data, uint32_t len)
{
uint32_t crc = 0xFFFFFFFF;
uint32_t gen_poly = 0xEDB88320;
for (uint32_t i = 0; i < len; i++)
{
crc ^= data[i];
for (uint8_t j = 0; j < 8; j++)
{
if (crc & 0x00000001)
crc = (crc >> 1) ^ gen_poly;
else
crc >>= 1;
}
}
return ~crc;
}
int main()
{
// 测试数据
uint8_t data[] = {0x01, 0x02, 0x03, 0x04, 0x05};
uint32_t len = sizeof(data);
// CRC8校验
uint8_t crc8 = calc_crc8(data, len);
cout << "CRC8: 0x" << hex << (int)crc8 << endl;
// CRC16校验
uint16_t crc16 = calc_crc16(data, len);
cout << "CRC16: 0x" << hex << crc16 << endl;
// CRC32校验
uint32_t crc32 = calc_crc32(data, len);
cout << "CRC32: 0x" << hex << crc32 << endl;
return 0;
}
```
注意,以上示例代码仅为演示CRC校验算法的实现,实际应用中可能需要对输入数据进行预处理(如填充、反转、异或等)以满足特定的校验需求。
阅读全文