libuav original

Dependents:   UAVCAN UAVCAN_Subscriber

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers crc.hpp Source File

crc.hpp

00001 /*
00002  * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
00003  */
00004 
00005 #ifndef UAVCAN_TRANSPORT_CRC_HPP_INCLUDED
00006 #define UAVCAN_TRANSPORT_CRC_HPP_INCLUDED
00007 
00008 #include <cassert>
00009 #include <uavcan/std.hpp>
00010 #include <uavcan/build_config.hpp>
00011 
00012 namespace uavcan
00013 {
00014 
00015 /**
00016  * CRC-16-CCITT
00017  * Initial value: 0xFFFF
00018  * Poly: 0x1021
00019  * Reverse: no
00020  * Output xor: 0
00021  *
00022  * import crcmod
00023  * crc = crcmod.predefined.Crc('crc-ccitt-false')
00024  * crc.update('123456789')
00025  * crc.hexdigest()
00026  * '29B1'
00027  */
00028 class UAVCAN_EXPORT TransferCRC
00029 {
00030 #if !UAVCAN_TINY
00031     static const uint16_t Table[256];
00032 #endif
00033 
00034     uint16_t value_;
00035 
00036 public:
00037     enum { NumBytes = 2 };
00038 
00039     TransferCRC()
00040         : value_(0xFFFFU)
00041     { }
00042 
00043 #if UAVCAN_TINY
00044     void add(uint8_t byte)
00045     {
00046         value_ ^= uint16_t(uint16_t(byte) << 8);
00047         for (uint8_t bit = 8; bit > 0; --bit)
00048         {
00049             if (value_ & 0x8000U)
00050             {
00051                 value_ = uint16_t(uint16_t(value_ << 1) ^ 0x1021U);
00052             }
00053             else
00054             {
00055                 value_ = uint16_t(value_ << 1);
00056             }
00057         }
00058     }
00059 #else
00060     void add(uint8_t byte)
00061     {
00062         value_ = uint16_t(uint16_t((value_ << 8) ^ Table[uint16_t((value_ >> 8) ^ byte) & 0xFFU]) & 0xFFFFU);
00063     }
00064 #endif
00065 
00066     void add(const uint8_t* bytes, unsigned len)
00067     {
00068         UAVCAN_ASSERT(bytes);
00069         while (len--)
00070         {
00071             add(*bytes++);
00072         }
00073     }
00074 
00075     uint16_t get() const { return value_; }
00076 };
00077 
00078 }
00079 
00080 #endif // UAVCAN_TRANSPORT_CRC_HPP_INCLUDED