| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #ifndef SVC_CCSDS_UTILS_CRC16_HPP | ||
| 2 | #define SVC_CCSDS_UTILS_CRC16_HPP | ||
| 3 | |||
| 4 | #include "Fw/Types/Assert.hpp" | ||
| 5 | #include "Fw/Types/BasicTypes.hpp" | ||
| 6 | // Include the libcrc library because we need update_crc_ccitt that is not provided through the main interface. | ||
| 7 | extern "C" { | ||
| 8 | #include <Utils/Hash/libcrc/lib_crc.h> | ||
| 9 | } | ||
| 10 | |||
| 11 | namespace Svc { | ||
| 12 | namespace Ccsds { | ||
| 13 | namespace Utils { | ||
| 14 | |||
| 15 | //! \brief CRC16 CCITT implementation | ||
| 16 | //! | ||
| 17 | //! CCSDS uses a CRC16 (CCITT) implementation with polynomial 0x1021, initial value of 0xFFFF, and XOR of 0x0000. | ||
| 18 | //! | ||
| 19 | class CRC16 { | ||
| 20 | public: | ||
| 21 | // Initial value is 0xFFFF | ||
| 22 | 2008 | CRC16() : m_crc(std::numeric_limits<U16>::max()) {} | |
| 23 | |||
| 24 | //! \brief update CRC with one new byte | ||
| 25 | //! | ||
| 26 | //! Update function for CRC taking previous value from member variable and updating it. | ||
| 27 | //! | ||
| 28 | //! \param new_byte: new byte to add to calculation | ||
| 29 | 30100 | void update(U8 new_byte) { this->m_crc = static_cast<U16>(update_crc_ccitt(m_crc, static_cast<char>(new_byte))); }; | |
| 30 | |||
| 31 | //! \brief finalize and return CRC value | ||
| 32 | 2008 | U16 finalize() { | |
| 33 | // Specified XOR value is 0x0000 | ||
| 34 | 2008 | return this->m_crc ^ static_cast<U16>(0); | |
| 35 | }; | ||
| 36 | |||
| 37 | //! \brief compute CRC16 for a buffer | ||
| 38 | //! | ||
| 39 | //! Compute the CRC16 for a given buffer and length. | ||
| 40 | //! | ||
| 41 | //! \param buffer: pointer to the data buffer | ||
| 42 | //! \param length: length of the data buffer | ||
| 43 | //! \return computed CRC16 value | ||
| 44 | 151 | static U16 compute(const U8* buffer, U32 length) { | |
| 45 | 151 | FW_ASSERT(buffer != nullptr); | |
| 46 | 151 | U16 crc = std::numeric_limits<U16>::max(); // Initial value | |
| 47 |
2/2✓ Branch 0 taken 65051 times.
✓ Branch 1 taken 151 times.
|
65202 | for (U32 i = 0; i < length; ++i) { |
| 48 | 65051 | crc = static_cast<U16>(update_crc_ccitt(crc, static_cast<char>(buffer[i]))); | |
| 49 | } | ||
| 50 | 151 | return crc ^ static_cast<U16>(0); // Finalize with XOR value | |
| 51 | } | ||
| 52 | |||
| 53 | U16 m_crc; | ||
| 54 | }; | ||
| 55 | |||
| 56 | } // namespace Utils | ||
| 57 | } // namespace Ccsds | ||
| 58 | } // namespace Svc | ||
| 59 | |||
| 60 | #endif // SVC_CCSDS_UTILS_CRC16_HPP | ||
| 61 |