#include "crc16.h" #include #include #include namespace { using CrcTable = std::array; CrcTable BuildCrcTable() { CrcTable table = {}; for (std::size_t index = 0; index < table.size(); ++index) { std::uint16_t value = static_cast(index << 8); for (int bit = 0; bit < 8; ++bit) { value = (value & 0x8000u) != 0 ? static_cast((value << 1) ^ 0x1021u) : static_cast(value << 1); } table[index] = value; } return table; } const CrcTable& GetCrcTable() { static const CrcTable table = BuildCrcTable(); return table; } } // namespace void CRC16_UpdateChecksum( std::uint16_t& crcValue, const void* data, const int length ) { assert(length >= 0); assert(data != nullptr || length == 0); if (length <= 0) { return; } const CrcTable& table = GetCrcTable(); const auto* bytes = static_cast(data); for (int index = 0; index < length; ++index) { const std::uint8_t tableIndex = static_cast( (crcValue >> 8) ^ bytes[index] ); crcValue = static_cast( table[tableIndex] ^ static_cast(crcValue << 8) ); } }