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
|
|
|
|
2017-04-21 23:03:20 +08:00
|
|
|
u16_t crc16(const u8_t *src, size_t len, u16_t polynomial,
|
2017-08-14 20:24:04 +08:00
|
|
|
u16_t initial_value, bool pad)
|
2017-03-30 17:54:29 +08:00
|
|
|
{
|
2017-04-21 23:03:20 +08:00
|
|
|
u16_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++) {
|
2019-03-15 02:55:21 +08:00
|
|
|
u16_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
|
|
|
|
|
|
|
u16_t crc16_ccitt(u16_t seed, const u8_t *src, size_t len)
|
|
|
|
{
|
|
|
|
for (; len > 0; len--) {
|
|
|
|
u8_t e, f;
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
u16_t crc16_itu_t(u16_t seed, const u8_t *src, size_t len)
|
|
|
|
{
|
|
|
|
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;
|
|
|
|
}
|