1 /*
2  * Copyright (c) 2023 Michal Morsisko
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/sys/crc.h>
8 
crc4(const uint8_t * src,size_t len,uint8_t polynomial,uint8_t initial_value,bool reversed)9 uint8_t crc4(const uint8_t *src, size_t len, uint8_t polynomial, uint8_t initial_value,
10 	  bool reversed)
11 {
12 	uint8_t crc = initial_value;
13 	size_t i, j, k;
14 
15 	for (i = 0; i < len; i++) {
16 		for (j = 0; j < 2; j++) {
17 			crc ^= ((src[i] >> (4 * (1 - j))) & 0xf);
18 
19 			for (k = 0; k < 4; k++) {
20 				if (reversed) {
21 					if (crc & 0x01) {
22 						crc = (crc >> 1) ^ polynomial;
23 					} else {
24 						crc >>= 1;
25 					}
26 				} else {
27 					if (crc & 0x8) {
28 						crc = (crc << 1) ^ polynomial;
29 					} else {
30 						crc <<= 1;
31 					}
32 				}
33 			}
34 		}
35 	}
36 
37 	return crc & 0xF;
38 }
39 
crc4_ti(uint8_t seed,const uint8_t * src,size_t len)40 uint8_t crc4_ti(uint8_t seed, const uint8_t *src, size_t len)
41 {
42 	static const uint8_t lookup[8] = { 0x03, 0x65, 0xcf, 0xa9, 0xb8, 0xde, 0x74, 0x12 };
43 	uint8_t index;
44 
45 	for (size_t i = 0; i < len; i++) {
46 		for (size_t j = 0U; j < 2U; j++) {
47 			index = seed ^ ((src[i] >> (4*(1-j))) & 0xf);
48 			seed = (lookup[index >> 1] >> (1 - (index & 1)) * 4) & 0xf;
49 		}
50 	}
51 
52 	return seed;
53 }
54