C++ 分别实现CRC8,CRC16,CRC32校验数据,并说明代码的功能作用
时间: 2023-11-28 07:49:48 浏览: 96
以下是C++代码实现CRC8、CRC16、CRC32校验数据的函数:
```c++
#include <iostream>
#include <bitset>
#include <vector>
// CRC8校验函数
uint8_t CRC8(const uint8_t* data, uint32_t length) {
const uint8_t poly = 0x07;
uint8_t crc = 0;
for (uint32_t i = 0; i < length; ++i) {
crc ^= data[i];
for (uint8_t j = 0; j < 8; ++j) {
if (crc & 0x80) {
crc = (crc << 1) ^ poly;
} else {
crc <<= 1;
}
}
}
return crc;
}
// CRC16校验函数
uint16_t CRC16(const uint8_t* data, uint32_t length) {
const uint16_t poly = 0x1021;
uint16_t crc = 0;
for (uint32_t i = 0; i < length; ++i) {
crc ^= (data[i] << 8);
for (uint8_t j = 0; j < 8; ++j) {
if (crc & 0x8000) {
crc = (crc << 1) ^ poly;
} else {
crc <<= 1;
}
}
}
return crc;
}
// CRC32校验函数
uint32_t CRC32(const uint8_t* data, uint32_t length) {
const uint32_t poly = 0xEDB88320;
uint32_t crc = 0xFFFFFFFF;
for (uint32_t i = 0; i < length; ++i) {
crc ^= data[i];
for (uint8_t j = 0; j < 8; ++j) {
if (crc & 0x00000001) {
crc = (crc >> 1) ^ poly;
} else {
crc >>= 1;
}
}
}
return ~crc;
}
int main() {
// 测试数据
std::vector<uint8_t> data = {0x01, 0x02, 0x03, 0x04, 0x05};
std::cout << "Data: ";
for (uint8_t byte : data) {
std::cout << std::bitset<8>(byte) << " ";
}
std::cout << std::endl;
// 计算CRC8校验值
uint8_t crc8 = CRC8(data.data(), data.size());
std::cout << "CRC8: " << std::bitset<8>(crc8) << std::endl;
// 计算CRC16校验值
uint16_t crc16 = CRC16(data.data(), data.size());
std::cout << "CRC16: " << std::bitset<16>(crc16) << std::endl;
// 计算CRC32校验值
uint32_t crc32 = CRC32(data.data(), data.size());
std::cout << "CRC32: " << std::bitset<32>(crc32) << std::endl;
return 0;
}
```
代码的功能作用是实现CRC8、CRC16、CRC32校验数据的函数,输入数据为一个指向数据缓冲区的指针和数据的长度,输出对应的CRC校验值。其中,CRC8校验使用的多项式为0x07,CRC16校验使用的多项式为0x1021,CRC32校验使用的多项式为0xEDB88320。在主函数中,我们输入了一个测试数据,并输出了计算得到的CRC8、CRC16、CRC32校验值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)