forked from zephyrproject-rtos/zephyr
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add two new functions: crc4 for generic calculations of CRC4, and crc4_ti which use look-up table for faster calculations of CRC4 algortihms that base on 0x03 polynomial. Signed-off-by: Michal Morsisko <[email protected]>
- Loading branch information
1 parent
d118ef5
commit 39aa2ad
Showing
3 changed files
with
95 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
/* | ||
* Copyright (c) 2023 Michal Morsisko | ||
* | ||
* SPDX-License-Identifier: Apache-2.0 | ||
*/ | ||
|
||
#include <zephyr/sys/crc.h> | ||
|
||
uint8_t crc4(const uint8_t *src, size_t len, uint8_t polynomial, uint8_t initial_value, | ||
bool reversed) | ||
{ | ||
uint8_t crc = initial_value; | ||
size_t i, j, k; | ||
|
||
for (i = 0; i < len; i++) { | ||
for (j = 0; j < 2; j++) { | ||
crc ^= ((src[i] >> (4 * (1 - j))) & 0xf); | ||
|
||
for (k = 0; k < 4; k++) { | ||
if (reversed) { | ||
if (crc & 0x01) { | ||
crc = (crc >> 1) ^ polynomial; | ||
} else { | ||
crc >>= 1; | ||
} | ||
} else { | ||
if (crc & 0x8) { | ||
crc = (crc << 1) ^ polynomial; | ||
} else { | ||
crc <<= 1; | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
return crc & 0xF; | ||
} | ||
|
||
uint8_t crc4_ti(uint8_t seed, const uint8_t *src, size_t len) | ||
{ | ||
static const uint8_t lookup[8] = { 0x03, 0x65, 0xcf, 0xa9, 0xb8, 0xde, 0x74, 0x12 }; | ||
uint8_t index; | ||
|
||
for (size_t i = 0; i < len; i++) { | ||
for (size_t j = 0U; j < 2U; j++) { | ||
index = seed ^ ((src[i] >> (4*(1-j))) & 0xf); | ||
seed = (lookup[index >> 1] >> (1 - (index & 1)) * 4) & 0xf; | ||
} | ||
} | ||
|
||
return seed; | ||
} |