Skip to content

Commit

Permalink
drivers: crc: Add 'pad' parameter to crc16()
Browse files Browse the repository at this point in the history
'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]>
  • Loading branch information
andrzej-kaczmarek authored and Anas Nashif committed Aug 18, 2017
1 parent 5d1fcfc commit 5d8eadd
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
7 changes: 4 additions & 3 deletions drivers/crc/crc16_sw.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@
#include <crc16.h>

u16_t crc16(const u8_t *src, size_t len, u16_t polynomial,
u16_t initial_value)
u16_t initial_value, bool pad)
{
u16_t crc = initial_value;
size_t padding = pad ? sizeof(crc) : 0;
size_t i, b;

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

for (b = 0; b < 8; b++) {
u16_t divide = crc & 0x8000;
Expand Down
8 changes: 5 additions & 3 deletions include/crc16.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#define __CRC16_H

#include <zephyr/types.h>
#include <stdbool.h>
#include <stddef.h>

/**
Expand All @@ -25,11 +26,12 @@
* @param polynomial The polynomial to use omitting the leading x^16
* coefficient
* @param initial_value Initial value for the CRC computation
* @param pad Adds padding with zeros at the end of input bytes
*
* @return The computed CRC16 value
*/
u16_t crc16(const u8_t *src, size_t len, u16_t polynomial,
u16_t initial_value);
u16_t initial_value, bool pad);

/**
* @brief Compute CCITT variant of CRC 16
Expand All @@ -44,7 +46,7 @@ u16_t crc16(const u8_t *src, size_t len, u16_t polynomial,
*/
static inline u16_t crc16_ccitt(const u8_t *src, size_t len)
{
return crc16(src, len, 0x1021, 0xffff);
return crc16(src, len, 0x1021, 0xffff, true);
}

/**
Expand All @@ -60,7 +62,7 @@ static inline u16_t crc16_ccitt(const u8_t *src, size_t len)
*/
static inline u16_t crc16_ansi(const u8_t *src, size_t len)
{
return crc16(src, len, 0x8005, 0xffff);
return crc16(src, len, 0x8005, 0xffff, true);
}

#endif

0 comments on commit 5d8eadd

Please sign in to comment.