diff --git a/sys/checksum/crc8.c b/sys/checksum/crc8.c new file mode 100644 index 0000000000..5a502c27a6 --- /dev/null +++ b/sys/checksum/crc8.c @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2018 Gunar Schorcht + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @ingroup sys_checksum_crc8 + * @brief CRC-8 checksum algorithms + * + * @{ + * + * @file + * @brief CRC-8 implementation + * + * @author Gunar Schorcht + */ + +#include +#include "checksum/crc8.h" + +uint8_t crc8(const uint8_t *data, size_t len, uint8_t g_polynom, uint8_t crc) +{ + /* iterate over all bytes */ + for (size_t i=0; i < len; i++) + { + crc ^= data[i]; + + for (int i = 0; i < 8; i++) + { + bool xor = crc & 0x80; + crc = crc << 1; + crc = xor ? crc ^ g_polynom : crc; + } + } + + return crc; +} + +/** @} */ diff --git a/sys/include/checksum/crc8.h b/sys/include/checksum/crc8.h new file mode 100644 index 0000000000..94523eed38 --- /dev/null +++ b/sys/include/checksum/crc8.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2018 Gunar Schorcht + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @defgroup sys_checksum_crc8 CRC-8 + * @ingroup sys_checksum + * @brief CRC-8 checksum algorithms + * + * @{ + * + * @file + * @brief CRC-8 definitions + * + * @author Gunar Schorcht + */ +#ifndef CHECKSUM_CRC8_H +#define CHECKSUM_CRC8_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Calculate CRC-8 + * + * @param[in] data Start of memory area to checksum + * @param[in] len Number of bytes in @p buf to calculate checksum for + * @param[in] poly The generator polynomial for the checksum + * @param[in] seed The seed (starting value) for the checksum + * + * @note Reflected inputs or outputs and final XOR must be realized + * by the caller if needed. + * + * @return Checksum of the specified memory area. + */ +uint8_t crc8(const uint8_t *data, size_t len, uint8_t poly, uint8_t seed); + +#ifdef __cplusplus +} +#endif + +#endif /* CHECKSUM_CRC8_H */ +/** @} */