#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;
}
