c++ 实现CRC-16 校验
时间: 2023-10-11 10:11:36 浏览: 167
以下是C++实现CRC-16校验的示例代码:
```c++
#include <iostream>
using namespace std;
unsigned short crc16(unsigned char *data, unsigned int length, unsigned short crc)
{
const unsigned short polynomial = 0x1021;
unsigned short crc_register = crc;
for (unsigned int i = 0; i < length; i++)
{
for (unsigned char bit = 0x80; bit > 0; bit >>= 1)
{
bool c15 = crc_register & 0x8000;
bool bit_in = data[i] & bit;
crc_register <<= 1;
if (bit_in != 0)
crc_register |= 0x0001;
if (c15 != 0)
crc_register ^= polynomial;
}
}
return crc_register;
}
int main()
{
unsigned char data[] = {0x01, 0x02, 0x03, 0x04};
unsigned int length = sizeof(data);
unsigned short crc = 0x0000;
unsigned short crc_result = crc16(data, length, crc);
cout << "CRC-16校验结果为:" << hex << crc_result << endl;
return 0;
}
```
其中,crc16函数接受三个参数:待校验数据的指针,数据长度和初始CRC值。在函数内部,我们使用了CRC-16的标准生成多项式0x1021进行计算,最后返回计算出的CRC校验值。在main函数中,我们将待校验数据赋值给data数组,调用crc16函数计算CRC-16校验值,并输出结果。
阅读全文