c++ crc16-ccitt 带输入反转输出反转代码
时间: 2023-08-28 10:03:26 浏览: 264
crc16-ccitt C语言代码
4星 · 用户满意度95%
以下是C++中计算CRC16-CCITT校验码,带输入反转和输出反转的代码实现:
```c++
#include <iostream>
#include <cstdint>
uint16_t crc16_ccitt(const uint8_t* data, size_t length) {
const uint16_t polynomial = 0x1021;
uint16_t crc = 0xFFFF;
for (size_t i = 0; i < length; ++i) {
crc ^= (uint16_t)data[i] << 8;
for (size_t j = 0; j < 8; ++j) {
if (crc & 0x8000) {
crc = (crc << 1) ^ polynomial;
} else {
crc <<= 1;
}
}
}
return crc;
}
uint16_t crc16_ccitt_input_reversed(const uint8_t* data, size_t length) {
uint8_t reversed_data[length];
for (size_t i = 0; i < length; ++i) {
reversed_data[length - i - 1] = data[i];
}
return crc16_ccitt(reversed_data, length);
}
uint16_t crc16_ccitt_output_reversed(const uint8_t* data, size_t length) {
uint16_t crc = crc16_ccitt(data, length);
uint16_t reversed_crc = 0;
for (size_t i = 0; i < 16; ++i) {
reversed_crc <<= 1;
reversed_crc |= crc & 1;
crc >>= 1;
}
return reversed_crc;
}
uint16_t crc16_ccitt_input_output_reversed(const uint8_t* data, size_t length) {
uint8_t reversed_data[length];
for (size_t i = 0; i < length; ++i) {
reversed_data[length - i - 1] = data[i];
}
uint16_t crc = crc16_ccitt(reversed_data, length);
uint16_t reversed_crc = 0;
for (size_t i = 0; i < 16; ++i) {
reversed_crc <<= 1;
reversed_crc |= crc & 1;
crc >>= 1;
}
return reversed_crc;
}
int main() {
uint8_t data[] = {0x01, 0x02, 0x03};
size_t length = sizeof(data) / sizeof(data[0]);
std::cout << std::hex << crc16_ccitt_input_reversed(data, length) << '\n';
std::cout << std::hex << crc16_ccitt_output_reversed(data, length) << '\n';
std::cout << std::hex << crc16_ccitt_input_output_reversed(data, length) << '\n';
return 0;
}
```
其中,`crc16_ccitt()`函数是计算CRC16-CCITT校验码的核心函数,`crc16_ccitt_input_reversed()`函数是带输入反转的计算函数,`crc16_ccitt_output_reversed()`函数是带输出反转的计算函数,`crc16_ccitt_input_output_reversed()`函数是同时带输入反转和输出反转的计算函数。在实际使用时,根据需要选择相应的函数进行计算即可。
阅读全文