CRC校验原理及简易c++实现
跟B站上的视频学了一遍CRC的计算过程,很清晰,可以看这个:
传送门
大致过程:
-
将校验多项式取系数。
如 \(x^4+x+1\) 可写为10011

-
在原数据末端加 k 个0


-
未处理的数据的1与校验多项式的系数对齐,每一项进行异或,再把得到的新数据串拼接回原数据串。再进行对齐操作。

CRC8的简易C++实现:
点击查看代码
#include<bits/stdc++.h>
using namespace std;
// CRC-8 计算类
class CRC8Calculator {
private:
uint8_t polynomial; // 生成多项式
uint8_t crc_value; // 当前CRC值
int byte_count; // 处理的字节数
public:
// 构造函数
CRC8Calculator(uint8_t poly = 0x07, uint8_t init = 0x00) {
polynomial = poly;
crc_value = init;
byte_count = 0;
}
// 重置计算器
void reset() {
crc_value = 0x00;
byte_count = 0;
}
// 处理单个字节
void addByte(uint8_t data_byte) {
crc_value ^= data_byte;
for (int i = 0; i < 8; i++) {
bool msb_is_one = (crc_value & 0x80) != 0;
if (msb_is_one) {
crc_value = (crc_value << 1) ^ polynomial;
} else {
crc_value = crc_value << 1;
}
}
byte_count++;
}
// 处理字节数组
void addBytes(const vector<uint8_t>& data_bytes) {
for (uint8_t byte : data_bytes) {
addByte(byte);
}
}
// 计算并返回CRC值
uint8_t getCRC() {
return crc_value;
}
// 显示信息
void showInfo() {
cout << "已处理字节数: " << byte_count << endl;
cout << "当前CRC值: 0x" << hex << (int)crc_value << dec << endl;
}
};
// 测试函数
int main() {
// 测试数据
vector<uint8_t> test_data = {0x01, 0x02, 0x03, 0x04, 0x05};
// 创建计算器
CRC8Calculator crc_calc;
// 计算CRC
cout << "=== CRC-8 计算示例 ===" << endl;
cout << "测试数据: ";
for (auto byte : test_data) {
cout << "0x" << hex << (int)byte << " ";
}
cout << dec << endl;
crc_calc.addBytes(test_data);
uint8_t result = crc_calc.getCRC();
// 显示结果
crc_calc.showInfo();
cout << endl;
// 验证示例
cout << "=== CRC 验证示例 ===" << endl;
// 完整数据(原始数据 + CRC)
vector<uint8_t> full_data = test_data;
full_data.push_back(result);
// 重新计算(应得到0)
CRC8Calculator verifier;
verifier.addBytes(full_data);
uint8_t verification = verifier.getCRC();
cout << "附加CRC后验证结果: 0x" << hex << (int)verification;
if (verification == 0) {
cout << " (验证通过)" << endl;
} else {
cout << " (验证失败)" << endl;
}
return 0;
}

浙公网安备 33010602011771号