我正在尝试为pic微控制器编写CRC8校验和的实现。我的算法基于this website上找到的算法,我的算法已经过测试并正在运行。
唯一的区别是我正在使我的CRC8函数将uint16_t作为输入并返回uint8_t作为输出,而不是二进制ascii值。我已经复制了他们的代码,但它似乎并没有让我得到与他们的代码相同的值。
#include <stdio.h>
#include <stdint.h>
uint8_t crc8(uint16_t input);
int main()
{
uint8_t temp1;
uint16_t temp2 = 0xAA79;
printf("CRC input is 0x%X\n", temp2);
temp1 = crc8(temp2);
printf("CRC output is 0x%X\n", temp1);
return 0;
}
uint8_t crc8(uint16_t input)
{
uint8_t crc[8] = { 0 };
uint8_t i;
uint8_t inv;
uint8_t output = 0;
for(i = 0; i < 16; i++)
{
inv = ((((input >> i) & 1) ^ crc[7]) & 1);
crc[7] = (crc[6] & 1);
crc[6] = (crc[5] & 1);
crc[5] = (crc[4] ^ inv & 1);
crc[4] = (crc[3] ^ inv & 1);
crc[3] = (crc[2] & 1);
crc[2] = (crc[1] & 1);
crc[1] = (crc[0] & 1);
crc[0] = (inv & 1);
}
for(i = 0; i < 8; i++)
{
output |= ((crc[i] << i) & (1 << i));
}
return output;
}
程序应该为0xAA79的输入返回值0x61。如果有人想知道,crc多项式是x ^ 8 + x ^ 5 + x ^ 4 + 1。
答案 0 :(得分:3)
您的程序 有效:但您的位顺序错误。以下是链接代码和您发布的代码。字符串bs[]
与temp2
具有相同的位序列但仍然失败。使用反转位字符串sb[]
的第二次尝试与您的函数输出匹配。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
uint8_t crc8(uint16_t input)
{
uint8_t crc[8] = { 0 };
uint8_t i;
uint8_t inv;
uint8_t output = 0;
for(i = 0; i < 16; i++)
{
inv = ((((input >> i) & 1) ^ crc[7]) & 1);
crc[7] = (crc[6] & 1);
crc[6] = (crc[5] & 1);
crc[5] = (crc[4] ^ inv & 1);
crc[4] = (crc[3] ^ inv & 1);
crc[3] = (crc[2] & 1);
crc[2] = (crc[1] & 1);
crc[1] = (crc[0] & 1);
crc[0] = (inv & 1);
}
for(i = 0; i < 8; i++)
{
output |= ((crc[i] << i) & (1 << i));
}
return output;
}
char *MakeCRC(char *BitString)
{
static char Res[9]; // CRC Result
char CRC[8];
int i;
char DoInvert;
for (i=0; i<8; ++i) CRC[i] = 0; // Init before calculation
for (i=0; i<strlen(BitString); ++i)
{
DoInvert = ('1'==BitString[i]) ^ CRC[7]; // XOR required?
CRC[7] = CRC[6];
CRC[6] = CRC[5];
CRC[5] = CRC[4] ^ DoInvert;
CRC[4] = CRC[3] ^ DoInvert;
CRC[3] = CRC[2];
CRC[2] = CRC[1];
CRC[1] = CRC[0];
CRC[0] = DoInvert;
}
for (i=0; i<8; ++i) Res[7-i] = CRC[i] ? '1' : '0'; // Convert binary to ASCII
Res[8] = 0; // Set string terminator
return(Res);
}
int main()
{
uint8_t temp1;
uint16_t temp2 = 0xAA79;
char bs[] = "1010101001111001";
char sb[] = "1001111001010101";
printf("CRC input is 0x%X\n", temp2);
temp1 = crc8(temp2);
printf("CRC output is 0x%X\n", temp1);
printf("Web ver output is %s\n", MakeCRC(bs));
printf("Web rev output is %s\n", MakeCRC(sb));
return 0;
}
节目输出:
CRC input is 0xAA79
CRC output is 0xAB
Web ver output is 01100001
Web rev output is 10101011