tool/sii_crc.cpp
changeset 1126 b09fd81894cb
child 1363 11c0b2caa253
equal deleted inserted replaced
1125:9976f7b9fe66 1126:b09fd81894cb
       
     1 /*****************************************************************************
       
     2  *
       
     3  * $Id$
       
     4  *
       
     5  ****************************************************************************/
       
     6 
       
     7 #include "sii_crc.h"
       
     8 
       
     9 /*****************************************************************************/
       
    10 
       
    11 /** Calculates the SII checksum field.
       
    12  *
       
    13  * The checksum is generated with the polynom x^8+x^2+x+1 (0x07) and an
       
    14  * initial value of 0xff (see IEC 61158-6-12 ch. 5.4).
       
    15  *
       
    16  * The below code was originally generated with PYCRC
       
    17  * http://www.tty1.net/pycrc
       
    18  *
       
    19  * ./pycrc.py --width=8 --poly=0x07 --reflect-in=0 --xor-in=0xff
       
    20  *   --reflect-out=0 --xor-out=0 --generate c --algorithm=bit-by-bit
       
    21  *
       
    22  * \return CRC8
       
    23  */
       
    24 uint8_t calcSiiCrc(
       
    25         const uint8_t *data, /**< pointer to data */
       
    26         size_t length /**< number of bytes in \a data */
       
    27         )
       
    28 {
       
    29     unsigned int i;
       
    30     uint8_t bit, byte, crc = 0x48;
       
    31 
       
    32     while (length--) {
       
    33         byte = *data++;
       
    34         for (i = 0; i < 8; i++) {
       
    35             bit = crc & 0x80;
       
    36             crc = (crc << 1) | ((byte >> (7 - i)) & 0x01);
       
    37             if (bit) crc ^= 0x07;
       
    38         }
       
    39     }
       
    40 
       
    41     for (i = 0; i < 8; i++) {
       
    42         bit = crc & 0x80;
       
    43         crc <<= 1;
       
    44         if (bit) crc ^= 0x07;
       
    45     }
       
    46 
       
    47     return crc;
       
    48 }
       
    49 
       
    50 /*****************************************************************************/