1 /*
2 * Copyright (c) 2020 Intel Corporation
3 * Copyright (c) 2017 Nordic Semiconductor ASA
4 * Copyright (c) 2015 Runtime Inc
5 *
6 * SPDX-License-Identifier: Apache-2.0
7 */
8
9 #include <sys/crc.h>
10
11 static const uint8_t crc8_ccitt_small_table[16] = {
12 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15,
13 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d
14 };
15
crc8_ccitt(uint8_t val,const void * buf,size_t cnt)16 uint8_t crc8_ccitt(uint8_t val, const void *buf, size_t cnt)
17 {
18 size_t i;
19 const uint8_t *p = buf;
20
21 for (i = 0; i < cnt; i++) {
22 val ^= p[i];
23 val = (val << 4) ^ crc8_ccitt_small_table[val >> 4];
24 val = (val << 4) ^ crc8_ccitt_small_table[val >> 4];
25 }
26 return val;
27 }
28
crc8(const uint8_t * src,size_t len,uint8_t polynomial,uint8_t initial_value,bool reversed)29 uint8_t crc8(const uint8_t *src, size_t len, uint8_t polynomial, uint8_t initial_value,
30 bool reversed)
31 {
32 uint8_t crc = initial_value;
33 size_t i, j;
34
35 for (i = 0; i < len; i++) {
36 crc ^= src[i];
37
38 for (j = 0; j < 8; j++) {
39 if (reversed) {
40 if (crc & 0x01) {
41 crc = (crc >> 1) ^ polynomial;
42 } else {
43 crc >>= 1;
44 }
45 } else {
46 if (crc & 0x80) {
47 crc = (crc << 1) ^ polynomial;
48 } else {
49 crc <<= 1;
50 }
51 }
52 }
53 }
54
55 return crc;
56 }
57