#include "modbus_crc.h"
#include "stdint.h"

static const uint16_t crc16_table[] = {
    0x0000, 0xcc01, 0xd801, 0x1400, 0xf001, 0x3c00, 0x2800, 0xe401,
    0xa001, 0x6c00, 0x7800, 0xb401, 0x5000, 0x9c01, 0x8801, 0x4400
};

uint16_t crc16_sub(const uint8_t *data, uint32_t length, uint16_t crc_val)
{
    while (length--) {
        uint8_t d = *data++;
        crc_val = (crc_val >> 4) ^ crc16_table[(crc_val ^ d) & 0xf];
        crc_val = (crc_val >> 4) ^ crc16_table[(crc_val ^ (d >> 4)) & 0xf];
    }
    return crc_val;
}
