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 		++src;
59 		f = e ^ (e << 4);
60 		seed = (seed >> 8) ^ ((uint16_t)f << 8) ^ ((uint16_t)f << 3) ^ ((uint16_t)f >> 4);
61 	}
62 
63 	return seed;
64 }
65 
crc16_itu_t(uint16_t seed,const uint8_t * src,size_t len)66 uint16_t crc16_itu_t(uint16_t seed, const uint8_t *src, size_t len)
67 {
68 	for (; len > 0; len--) {
69 		seed = (seed >> 8U) | (seed << 8U);
70 		seed ^= *src;
71 		++src;
72 		seed ^= (seed & 0xffU) >> 4U;
73 		seed ^= seed << 12U;
74 		seed ^= (seed & 0xffU) << 5U;
75 	}
76 
77 	return seed;
78 }
79