crc16

看到一个很不错的crc16的函数,顺便写了一个小小的测试例子:

#include<stdio.h>

#define  uint16_t unsigned short

#define  uint8_t unsigned char

/*******************************************************************************

 * @fn          crc16

 *

 * @brief       Run the CRC16 Polynomial calculation over the byte parameter.

 *

 * @param       crc - Running CRC calculated so far.

 * @param       val - Value on which to run the CRC16.

 *

 * @return      crc - Updated for the run.

 */

uint16_t crc16(uint16_t crc, uint8_t val)

{

  const uint16_t poly = 0x1021;

  uint8_t cnt;

  for (cnt = 0; cnt < 8; cnt++, val <<= 1)

  {

    uint8_t msb = (crc & 0x8000) ? 1 : 0;

    crc <<= 1;

    if (val & 0x80)

    {

      crc |= 0x0001;

    }

    if (msb)

    {

      crc ^= poly;

    }

  }

  return crc;

}

int main(){

    uint16_t crc = 0;

    uint8_t buf_value[10] = {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a};

    int i;

    for(i = 0;i < 10;i++){

        crc = crc16(crc, buf_value[i]);

    }

    printf("%x\n",crc);

    

    crc = 0;

    for(i = 0;i < 10;i++){

        crc = crc16(crc, buf_value[i]);

    }

    printf("%x\n",crc);

    

    return 0;

}

运行结果:

以上是 crc16 的全部内容, 来源链接: utcz.com/a/53981.html

回到顶部