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 <zephyr/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
16 static const uint8_t crc8_rohc_small_table[16] = {
17 0x00, 0x1c, 0x38, 0x24, 0x70, 0x6c, 0x48, 0x54,
18 0xe0, 0xfc, 0xd8, 0xc4, 0x90, 0x8c, 0xa8, 0xb4
19 };
20
crc8_ccitt(uint8_t val,const void * buf,size_t cnt)21 uint8_t crc8_ccitt(uint8_t val, const void *buf, size_t cnt)
22 {
23 size_t i;
24 const uint8_t *p = buf;
25
26 for (i = 0; i < cnt; i++) {
27 val ^= p[i];
28 val = (val << 4) ^ crc8_ccitt_small_table[val >> 4];
29 val = (val << 4) ^ crc8_ccitt_small_table[val >> 4];
30 }
31 return val;
32 }
33
crc8_rohc(uint8_t val,const void * buf,size_t cnt)34 uint8_t crc8_rohc(uint8_t val, const void *buf, size_t cnt)
35 {
36 size_t i;
37 const uint8_t *p = buf;
38
39 for (i = 0; i < cnt; i++) {
40 val ^= p[i];
41 val = (val >> 4) ^ crc8_rohc_small_table[val & 0x0f];
42 val = (val >> 4) ^ crc8_rohc_small_table[val & 0x0f];
43 }
44 return val;
45 }
46
crc8(const uint8_t * src,size_t len,uint8_t polynomial,uint8_t initial_value,bool reversed)47 uint8_t crc8(const uint8_t *src, size_t len, uint8_t polynomial, uint8_t initial_value,
48 bool reversed)
49 {
50 uint8_t crc = initial_value;
51 size_t i, j;
52
53 for (i = 0; i < len; i++) {
54 crc ^= src[i];
55
56 for (j = 0; j < 8; j++) {
57 if (reversed) {
58 if ((crc & 0x01) != 0) {
59 crc = (crc >> 1) ^ polynomial;
60 } else {
61 crc >>= 1;
62 }
63 } else {
64 if ((crc & 0x80) != 0) {
65 crc = (crc << 1) ^ polynomial;
66 } else {
67 crc <<= 1;
68 }
69 }
70 }
71 }
72
73 return crc;
74 }
75