blob: 67043d27c501d13d497ffe7b0b8579a61b8504b4 [file] [log] [blame]
Andrzej Puzdrowski9a5a3e02017-12-13 14:57:38 +01001/*
Jukka Rissanen9d4fbb22020-02-26 13:44:42 +02002 * Copyright (c) 2020 Intel Corporation
Andrzej Puzdrowski9a5a3e02017-12-13 14:57:38 +01003 * Copyright (c) 2017 Nordic Semiconductor ASA
4 * Copyright (c) 2015 Runtime Inc
5 *
6 * SPDX-License-Identifier: Apache-2.0
7 */
8
Gerard Marull-Paretascbd31d72022-05-06 11:23:05 +02009#include <zephyr/sys/crc.h>
Andrzej Puzdrowski9a5a3e02017-12-13 14:57:38 +010010
Kumar Galaa1b77fd2020-05-27 11:26:57 -050011static const uint8_t crc8_ccitt_small_table[16] = {
Andrzej Puzdrowski9a5a3e02017-12-13 14:57:38 +010012 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15,
13 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d
14};
15
Kumar Galaa1b77fd2020-05-27 11:26:57 -050016uint8_t crc8_ccitt(uint8_t val, const void *buf, size_t cnt)
Andrzej Puzdrowski9a5a3e02017-12-13 14:57:38 +010017{
Joakim Andersson4ebfafe2020-04-03 18:55:04 +020018 size_t i;
Kumar Galaa1b77fd2020-05-27 11:26:57 -050019 const uint8_t *p = buf;
Andrzej Puzdrowski9a5a3e02017-12-13 14:57:38 +010020
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}
Jukka Rissanen9d4fbb22020-02-26 13:44:42 +020028
Kumar Galaa1b77fd2020-05-27 11:26:57 -050029uint8_t crc8(const uint8_t *src, size_t len, uint8_t polynomial, uint8_t initial_value,
Jukka Rissanen9d4fbb22020-02-26 13:44:42 +020030 bool reversed)
31{
Kumar Galaa1b77fd2020-05-27 11:26:57 -050032 uint8_t crc = initial_value;
Jukka Rissanen9d4fbb22020-02-26 13:44:42 +020033 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}