optimize math (#5287)
[betaflight.git] / src / main / common / crc.c
blob6150e8b40c4ae18a26bbba400666d470addaeaad
1 /*
2 * This file is part of Cleanflight.
4 * Cleanflight is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * Cleanflight is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with Cleanflight. If not, see <http://www.gnu.org/licenses/>.
18 #include <stdint.h>
20 #include "streambuf.h"
23 uint16_t crc16_ccitt(uint16_t crc, unsigned char a)
25 crc ^= (uint16_t)a << 8;
26 for (int ii = 0; ii < 8; ++ii) {
27 if (crc & 0x8000) {
28 crc = (crc << 1) ^ 0x1021;
29 } else {
30 crc = crc << 1;
33 return crc;
36 uint16_t crc16_ccitt_update(uint16_t crc, const void *data, uint32_t length)
38 const uint8_t *p = (const uint8_t *)data;
39 const uint8_t *pend = p + length;
41 for (; p != pend; p++) {
42 crc = crc16_ccitt(crc, *p);
44 return crc;
47 void crc16_ccitt_sbuf_append(sbuf_t *dst, uint8_t *start)
49 uint16_t crc = 0;
50 const uint8_t * const end = sbufPtr(dst);
51 for (const uint8_t *ptr = start; ptr < end; ++ptr) {
52 crc = crc16_ccitt(crc, *ptr);
54 sbufWriteU16(dst, crc);
57 uint8_t crc8_dvb_s2(uint8_t crc, unsigned char a)
59 crc ^= a;
60 for (int ii = 0; ii < 8; ++ii) {
61 if (crc & 0x80) {
62 crc = (crc << 1) ^ 0xD5;
63 } else {
64 crc = crc << 1;
67 return crc;
70 uint8_t crc8_dvb_s2_update(uint8_t crc, const void *data, uint32_t length)
72 const uint8_t *p = (const uint8_t *)data;
73 const uint8_t *pend = p + length;
75 for (; p != pend; p++) {
76 crc = crc8_dvb_s2(crc, *p);
78 return crc;
81 void crc8_dvb_s2_sbuf_append(sbuf_t *dst, uint8_t *start)
83 uint8_t crc = 0;
84 const uint8_t * const end = dst->ptr;
85 for (const uint8_t *ptr = start; ptr < end; ++ptr) {
86 crc = crc8_dvb_s2(crc, *ptr);
88 sbufWriteU8(dst, crc);
91 uint8_t crc8_xor_update(uint8_t crc, const void *data, uint32_t length)
93 const uint8_t *p = (const uint8_t *)data;
94 const uint8_t *pend = p + length;
96 for (; p != pend; p++) {
97 crc ^= *p;
99 return crc;
102 void crc8_xor_sbuf_append(sbuf_t *dst, uint8_t *start)
104 uint8_t crc = 0;
105 const uint8_t *end = dst->ptr;
106 for (uint8_t *ptr = start; ptr < end; ++ptr) {
107 crc ^= *ptr;
109 sbufWriteU8(dst, crc);