#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//获取长度
size_t calculateLength(uint8_t *temp)
{
size_t len = 0;
while (temp[len] != '\0')
{
len++;
}
return len;
}
//字符串转uint8_t*
uint8_t* charToUint8(char* data) {
int len = strlen(data);
uint8_t* result = (uint8_t*)malloc(len / 2);
for (int i = 0; i < len; i += 2) {
sscanf(data + i, "%2hhx", &result[i / 2]);
}
return result;
}
uint8_t crc8(uint8_t *data, int len)
{
uint8_t crc = 0;
uint8_t poly = 0xE5; // 多项式 X^7 + X^6 + X^5 + X^2 + 1 对应的十六进制表示
for (int i = 0; i < len; i++)
{
crc ^= data[i];
for (int j = 0; j < 8; j++)
{
if (crc & 0x80)
{
crc = (crc << 1) ^ poly;
}
else
{
crc <<= 1;
}
}
}
return crc;
}
//测试
int main(int argc, char *argv[])
{
if (argc <= 1)
{
return 0;
}
uint8_t *data = charToUint8(argv[1]);
int len = calculateLength(argv[1])/2;
uint8_t crc7 = crc8(data, len);
printf("******\n");
for(int i = 0;i<len;i++){
printf("%.2x ", data[i]);
}
printf("\ncrc7 = %x\n******\n", crc7);
return 1;
}
测试结果: