1 /*
2  * Copyright (c) 2017 Intel Corporation.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/sys/crc.h>
8 
crc16(uint16_t poly,uint16_t seed,const uint8_t * src,size_t len)9 uint16_t crc16(uint16_t poly, uint16_t seed, const uint8_t *src, size_t len)
10 {
11 	uint16_t crc = seed;
12 	size_t i, j;
13 
14 	for (i = 0; i < len; i++) {
15 		crc ^= (uint16_t)(src[i] << 8U);
16 
17 		for (j = 0; j < 8; j++) {
18 			if (crc & 0x8000UL) {
19 				crc = (crc << 1U) ^ poly;
20 			} else {
21 				crc = crc << 1U;
22 			}
23 		}
24 	}
25 
26 
27 	return crc;
28 }
29 
crc16_reflect(uint16_t poly,uint16_t seed,const uint8_t * src,size_t len)30 uint16_t crc16_reflect(uint16_t poly, uint16_t seed, const uint8_t *src, size_t len)
31 {
32 	uint16_t crc = seed;
33 	size_t i, j;
34 
35 	for (i = 0; i < len; i++) {
36 		crc ^= (uint16_t)src[i];
37 
38 		for (j = 0; j < 8; j++) {
39 			if (crc & 0x0001UL) {
40 				crc = (crc >> 1U) ^ poly;
41 			} else {
42 				crc = crc >> 1U;
43 			}
44 		}
45 	}
46 
47 
48 	return crc;
49 }
50 
51 
crc16_ccitt(uint16_t seed,const uint8_t * src,size_t len)52 uint16_t crc16_ccitt(uint16_t seed, const uint8_t *src, size_t len)
53 {
54 	for (; len > 0; len--) {
55 		uint8_t e, f;
56 
57 		e = seed ^ *src++;
58 		f = e ^ (e << 4);
59 		seed = (seed >> 8) ^ ((uint16_t)f << 8) ^ ((uint16_t)f << 3) ^ ((uint16_t)f >> 4);
60 	}
61 
62 	return seed;
63 }
64 
crc16_itu_t(uint16_t seed,const uint8_t * src,size_t len)65 uint16_t crc16_itu_t(uint16_t seed, const uint8_t *src, size_t len)
66 {
67 	for (; len > 0; len--) {
68 		seed = (seed >> 8U) | (seed << 8U);
69 		seed ^= *src++;
70 		seed ^= (seed & 0xffU) >> 4U;
71 		seed ^= seed << 12U;
72 		seed ^= (seed & 0xffU) << 5U;
73 	}
74 
75 	return seed;
76 }
77