iT邦幫忙

0

CRC-8-CCITT

  • 分享至 

  • xImage
  •  

CRC-8-CCITT
SMBus PEC

/* https://en.wikipedia.org/wiki/System_Management_Bus#Packet_Error_Checking */
/* https://blog.csdn.net/zjli321/article/details/52998468 */
/* https://crccalc.com/ */
#include <stdio.h>

// cal_table_high_first
unsigned char crc8(unsigned char value)
{
    unsigned char i, crc;

    crc = value;
    /* 数据往左移了8位,需要计算8次 */
    for (i=8; i>0; --i)
    { 
        if (crc & 0x80)  /* 判断最高位是否为1 */
        {
        /* 最高位为1,不需要异或,往左移一位,然后与0x07异或 */
        /* 0x07(多项式:x^8+x^3+x^2+1,100000111),最高位不需要异或,直接去掉 */
            crc = (crc << 1) ^ 0x07;        }
        else
        {
            /* 最高位为0时,不需要异或,整体数据往左移一位 */
            crc = (crc << 1);
        }
    }

    return crc;
}

unsigned int crc8_checksum(unsigned int value)
{
  unsigned char d = 0x00, result = 0x00;

  for (int i = sizeof(value); i > 0; --i)
  {
    d = value >> (8 * (i-1));
    result = crc8(result ^ d);
  }
  return result;
}

int main(void) {
  printf("Hello World\n");
  printf("%X\n", crc8(0xB1));
  printf("%X\n", crc8(crc8(0xB1) ^ 0x6A));
  printf("%X\n", crc8(crc8(crc8(0xB1) ^ 0x6A) ^ 0x03));
  printf("\n");
  printf("%02X\n", crc8_checksum(0xB16A03));
  printf("\n");
  
  printf("%02X\n", crc8(0xB0));
  printf("%02X\n", crc8(crc8(0xB0) ^ 0x6A));
  printf("%02X\n", crc8(crc8(crc8(0xB0) ^ 0x6A) ^ 0x30));
  printf("%02X\n", crc8(crc8(crc8(crc8(0xB0) ^ 0x6A) ^ 0x30) ^ 0x20));
  printf("\n");
  printf("%02X\n", crc8_checksum(0xB06A3020));
  printf("\n");
  return 0;
}

https://en.wikipedia.org/wiki/Cyclic_redundancy_check
https://crccalc.com/
https://blog.csdn.net/zjli321/article/details/52998468
http://lms.ctl.cyut.edu.tw/sys/read_attach.php?id=1871500
http://wiki.csie.ncku.edu.tw/embedded/I2C


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言