examples

Toy examples in single C files.
git clone git://henryandlizzy.uk/examples
Log | Files | Refs

crc7.cpp (1671B)


      1 #include <iostream>
      2 #include <cstdint>
      3 #include <vector>
      4 #include <array>
      5 #include <iterator>
      6 
      7 uint8_t CRCTable[256];
      8  
      9 void GenerateCRCTable()
     10 {
     11   int i, j;
     12   uint8_t CRCPoly = 0x89;  // the value of our CRC-7 polynomial
     13  
     14   // generate a table value for all 256 possible byte values
     15   for (i = 0; i < 256; ++i) {
     16     CRCTable[i] = (i & 0x80) ? i ^ CRCPoly : i;
     17     for (j = 1; j < 8; ++j) {
     18         CRCTable[i] <<= 1;
     19         if (CRCTable[i] & 0x80)
     20             CRCTable[i] ^= CRCPoly;
     21     }
     22   }
     23 }
     24  
     25 // adds a message byte to the current CRC-7 to get a the new CRC-7
     26 uint8_t CRCAdd(uint8_t CRC, uint8_t message_byte)
     27 {
     28     return CRCTable[(CRC << 1) ^ message_byte];
     29 }
     30  
     31 // returns the CRC-7 for a message of "length" bytes
     32 uint8_t getCRC(uint8_t message[], int length)
     33 {
     34   int i;
     35   uint8_t CRC = 0;
     36 
     37   for (i = 0; i < length; ++i)
     38     CRC = CRCAdd(CRC, message[i]);
     39 
     40   return CRC;
     41 }
     42 
     43 void PrintFrame(std::array<uint8_t, 6> & f)
     44 {
     45   for (auto e : f)
     46     std::cout << std::hex << (int) e << " ";
     47   std::cout << std::endl;
     48 }
     49 
     50 int main()
     51 {
     52   GenerateCRCTable();
     53 
     54   std::copy(std::begin(CRCTable), std::end(CRCTable), std::ostream_iterator<unsigned>(std::cout, ", "));
     55 
     56   std::vector<std::array<uint8_t, 6>> CommandFrames;
     57   CommandFrames.push_back({{0x40, 0, 0, 0, 0, 0}});
     58   CommandFrames.push_back({{0x48, 0, 0, 1, 0xAA, 0}});
     59   CommandFrames.push_back({{0x69, 0x40, 0, 0, 0, 0}});
     60   CommandFrames.push_back({{0x77, 0x00, 0, 0, 0, 0}});
     61   CommandFrames.push_back({{0x7A, 0x00, 0, 0, 0, 0}});
     62 
     63   std::cout << "\n\nCommand, Argument, CRC7" << std::endl;
     64   for (auto &Frame : CommandFrames) {
     65     Frame[5] = (getCRC(Frame.data(), 5) << 1) | 1;
     66     PrintFrame(Frame);
     67   }
     68 }