Andrzej Puzdrowski | 9a5a3e0 | 2017-12-13 14:57:38 +0100 | [diff] [blame] | 1 | /* |
Jukka Rissanen | 9d4fbb2 | 2020-02-26 13:44:42 +0200 | [diff] [blame] | 2 | * Copyright (c) 2020 Intel Corporation |
Andrzej Puzdrowski | 9a5a3e0 | 2017-12-13 14:57:38 +0100 | [diff] [blame] | 3 | * Copyright (c) 2017 Nordic Semiconductor ASA |
| 4 | * Copyright (c) 2015 Runtime Inc |
| 5 | * |
| 6 | * SPDX-License-Identifier: Apache-2.0 |
| 7 | */ |
| 8 | |
Gerard Marull-Paretas | cbd31d7 | 2022-05-06 11:23:05 +0200 | [diff] [blame] | 9 | #include <zephyr/sys/crc.h> |
Andrzej Puzdrowski | 9a5a3e0 | 2017-12-13 14:57:38 +0100 | [diff] [blame] | 10 | |
Kumar Gala | a1b77fd | 2020-05-27 11:26:57 -0500 | [diff] [blame] | 11 | static const uint8_t crc8_ccitt_small_table[16] = { |
Andrzej Puzdrowski | 9a5a3e0 | 2017-12-13 14:57:38 +0100 | [diff] [blame] | 12 | 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, |
| 13 | 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d |
| 14 | }; |
| 15 | |
Kumar Gala | a1b77fd | 2020-05-27 11:26:57 -0500 | [diff] [blame] | 16 | uint8_t crc8_ccitt(uint8_t val, const void *buf, size_t cnt) |
Andrzej Puzdrowski | 9a5a3e0 | 2017-12-13 14:57:38 +0100 | [diff] [blame] | 17 | { |
Joakim Andersson | 4ebfafe | 2020-04-03 18:55:04 +0200 | [diff] [blame] | 18 | size_t i; |
Kumar Gala | a1b77fd | 2020-05-27 11:26:57 -0500 | [diff] [blame] | 19 | const uint8_t *p = buf; |
Andrzej Puzdrowski | 9a5a3e0 | 2017-12-13 14:57:38 +0100 | [diff] [blame] | 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 | } |
Jukka Rissanen | 9d4fbb2 | 2020-02-26 13:44:42 +0200 | [diff] [blame] | 28 | |
Kumar Gala | a1b77fd | 2020-05-27 11:26:57 -0500 | [diff] [blame] | 29 | uint8_t crc8(const uint8_t *src, size_t len, uint8_t polynomial, uint8_t initial_value, |
Jukka Rissanen | 9d4fbb2 | 2020-02-26 13:44:42 +0200 | [diff] [blame] | 30 | bool reversed) |
| 31 | { |
Kumar Gala | a1b77fd | 2020-05-27 11:26:57 -0500 | [diff] [blame] | 32 | uint8_t crc = initial_value; |
Jukka Rissanen | 9d4fbb2 | 2020-02-26 13:44:42 +0200 | [diff] [blame] | 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 | } |