2017-03-30 17:54:29 +08:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2017 Intel Corporation.
|
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include <crc16.h>
|
|
|
|
|
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++) {
|
2017-04-21 23:03:20 +08:00
|
|
|
u16_t divide = crc & 0x8000;
|
2017-03-30 17:54:29 +08:00
|
|
|
|
|
|
|
crc = (crc << 1);
|
|
|
|
|
|
|
|
/* choose input bytes or implicit trailing zeros */
|
|
|
|
if (i < len) {
|
|
|
|
crc |= !!(src[i] & (0x80 >> b));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (divide) {
|
|
|
|
crc = crc ^ polynomial;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return crc;
|
|
|
|
}
|