2017-03-30 17:54:29 +08:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2017 Intel Corporation.
|
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
|
|
*/
|
|
|
|
|
2019-06-26 00:25:56 +08:00
|
|
|
#include <sys/crc.h>
|
2017-03-30 17:54:29 +08:00
|
|
|
|
2020-05-28 00:26:57 +08:00
|
|
|
uint16_t crc16(const uint8_t *src, size_t len, uint16_t polynomial,
|
|
|
|
uint16_t initial_value, bool pad)
|
2017-03-30 17:54:29 +08:00
|
|
|
{
|
2020-05-28 00:26:57 +08:00
|
|
|
uint16_t crc = initial_value;
|
2017-08-14 20:24:04 +08:00
|
|
|
size_t padding = pad ? sizeof(crc) : 0;
|
2017-03-30 17:54:29 +08:00
|
|
|
size_t i, b;
|
|
|
|
|
2017-08-14 20:24:04 +08:00
|
|
|
/* src length + padding (if required) */
|
|
|
|
for (i = 0; i < len + padding; i++) {
|
2017-03-30 17:54:29 +08:00
|
|
|
|
|
|
|
for (b = 0; b < 8; b++) {
|
2020-05-28 00:26:57 +08:00
|
|
|
uint16_t divide = crc & 0x8000UL;
|
2017-03-30 17:54:29 +08:00
|
|
|
|
2019-03-15 02:55:21 +08:00
|
|
|
crc = (crc << 1U);
|
2017-03-30 17:54:29 +08:00
|
|
|
|
|
|
|
/* choose input bytes or implicit trailing zeros */
|
|
|
|
if (i < len) {
|
2019-03-15 02:55:21 +08:00
|
|
|
crc |= !!(src[i] & (0x80U >> b));
|
2017-03-30 17:54:29 +08:00
|
|
|
}
|
|
|
|
|
2019-03-29 04:57:54 +08:00
|
|
|
if (divide != 0U) {
|
2017-03-30 17:54:29 +08:00
|
|
|
crc = crc ^ polynomial;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return crc;
|
|
|
|
}
|
2017-11-28 05:06:02 +08:00
|
|
|
|
2020-05-28 00:26:57 +08:00
|
|
|
uint16_t crc16_ccitt(uint16_t seed, const uint8_t *src, size_t len)
|
2017-11-28 05:06:02 +08:00
|
|
|
{
|
|
|
|
for (; len > 0; len--) {
|
2020-05-28 00:26:57 +08:00
|
|
|
uint8_t e, f;
|
2017-11-28 05:06:02 +08:00
|
|
|
|
|
|
|
e = seed ^ *src++;
|
|
|
|
f = e ^ (e << 4);
|
|
|
|
seed = (seed >> 8) ^ (f << 8) ^ (f << 3) ^ (f >> 4);
|
|
|
|
}
|
|
|
|
|
|
|
|
return seed;
|
|
|
|
}
|
2018-02-02 04:37:24 +08:00
|
|
|
|
2020-05-28 00:26:57 +08:00
|
|
|
uint16_t crc16_itu_t(uint16_t seed, const uint8_t *src, size_t len)
|
2018-02-02 04:37:24 +08:00
|
|
|
{
|
|
|
|
for (; len > 0; len--) {
|
2019-03-15 02:55:21 +08:00
|
|
|
seed = (seed >> 8U) | (seed << 8U);
|
2018-02-02 04:37:24 +08:00
|
|
|
seed ^= *src++;
|
2019-03-15 02:55:21 +08:00
|
|
|
seed ^= (seed & 0xffU) >> 4U;
|
|
|
|
seed ^= seed << 12U;
|
|
|
|
seed ^= (seed & 0xffU) << 5U;
|
2018-02-02 04:37:24 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return seed;
|
|
|
|
}
|