This repository has been archived on 2025-07-31. You can view files and clone it, but cannot push or open issues or pull requests.
SP713_Upper_C/apps/crc16/crc.cpp
2025-07-17 13:10:47 +08:00

43 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "crc.h"
// 函数声明
// void generate_crc16_reverse_table(quint16 *table);
// QByteArray crc16Reverse(const QByteArray& data);
static void generate_crc16_reverse_table(quint16 table[256], quint16 poly = 0x8408)
{
for (int i = 0; i < 256; ++i) {
quint16 crc = static_cast<quint16>(i);
for (int j = 0; j < 8; ++j) {
if (crc & 0x0001)
crc = (crc >> 1) ^ poly;
else
crc >>= 1;
}
table[i] = crc;
}
}
// 计算反射型CRC16-CCITT
QByteArray crc16Reverse(const QByteArray& data)
{
static quint16 table[256];
static bool tableInited = false;
if (!tableInited) {
generate_crc16_reverse_table(table);
tableInited = true;
}
quint16 crc = 0x6363;
for (auto b : data)
crc = (crc >> 8) ^ table[(crc ^ static_cast<quint8>(b)) & 0xFF];
QByteArray result;
// 经过和python程序对比说明CRC16的两个byte位置需调换
// result.append(static_cast<char>((crc >> 8) & 0xFF));
// result.append(static_cast<char>(crc & 0xFF));
result.append(static_cast<char>(crc & 0xFF));
result.append(static_cast<char>((crc >> 8) & 0xFF));
return result;
}