Skip to content

Commit 5d8eadd

Browse files
andrzej-kaczmarekAnas Nashif
authored andcommitted
drivers: crc: Add 'pad' parameter to crc16()
'pad' parameter controls whether crc16() should add padding at the end of input bytes or not. This allows to compute CRC16 for data stored in non-contiguous buffers where CRC value is calculated using subsequent calls to crc16() with padding added only for last chunk. Signed-off-by: Andrzej Kaczmarek <[email protected]>
1 parent 5d1fcfc commit 5d8eadd

File tree

2 files changed

+9
-6
lines changed

2 files changed

+9
-6
lines changed

drivers/crc/crc16_sw.c

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,14 @@
77
#include <crc16.h>
88

99
u16_t crc16(const u8_t *src, size_t len, u16_t polynomial,
10-
u16_t initial_value)
10+
u16_t initial_value, bool pad)
1111
{
1212
u16_t crc = initial_value;
13+
size_t padding = pad ? sizeof(crc) : 0;
1314
size_t i, b;
1415

15-
/* src length + crc width of zeros appended */
16-
for (i = 0; i < len + sizeof(crc); i++) {
16+
/* src length + padding (if required) */
17+
for (i = 0; i < len + padding; i++) {
1718

1819
for (b = 0; b < 8; b++) {
1920
u16_t divide = crc & 0x8000;

include/crc16.h

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#define __CRC16_H
1313

1414
#include <zephyr/types.h>
15+
#include <stdbool.h>
1516
#include <stddef.h>
1617

1718
/**
@@ -25,11 +26,12 @@
2526
* @param polynomial The polynomial to use omitting the leading x^16
2627
* coefficient
2728
* @param initial_value Initial value for the CRC computation
29+
* @param pad Adds padding with zeros at the end of input bytes
2830
*
2931
* @return The computed CRC16 value
3032
*/
3133
u16_t crc16(const u8_t *src, size_t len, u16_t polynomial,
32-
u16_t initial_value);
34+
u16_t initial_value, bool pad);
3335

3436
/**
3537
* @brief Compute CCITT variant of CRC 16
@@ -44,7 +46,7 @@ u16_t crc16(const u8_t *src, size_t len, u16_t polynomial,
4446
*/
4547
static inline u16_t crc16_ccitt(const u8_t *src, size_t len)
4648
{
47-
return crc16(src, len, 0x1021, 0xffff);
49+
return crc16(src, len, 0x1021, 0xffff, true);
4850
}
4951

5052
/**
@@ -60,7 +62,7 @@ static inline u16_t crc16_ccitt(const u8_t *src, size_t len)
6062
*/
6163
static inline u16_t crc16_ansi(const u8_t *src, size_t len)
6264
{
63-
return crc16(src, len, 0x8005, 0xffff);
65+
return crc16(src, len, 0x8005, 0xffff, true);
6466
}
6567

6668
#endif

0 commit comments

Comments
 (0)