很多单片机例如STM、NXP等都在硬件上实现了CRC计算引擎,上位机与其通信,如果有CRC32计算的话,需要统一两端的CRC32算法,网上找的一些我看都不靠谱,计算结果和单片机上的结果不一致,我贴一下我写的代码吧。
#include
#include
//{0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, ...}
//hello: E6CE9AC2
static uint32_t CRC32Table[256];
void CRC32_Init(int order)
{
uint32_t poly;
int i;
if(order)
poly = 0x4C11DB7;
else
poly = 0xEDB88320;
for(i = 0; i < 256; i++)
{
uint32_t crc = order ? i << 24 : i;
int j;
for (j = 0; j < 8; j++)
{
if(order)
{
crc = (crc & 0x80000000) ? (poly ^ (crc << 1)) : (crc << 1);
}
else
{
crc = (crc & 1) ? (poly ^ (crc >> 1)) : (crc >> 1);
}
}
CRC32Table = crc;
}
}
uint32_t CRC32_Calc(void *buf, int len)
{
uint32_t crc = -1;
int i;
for(i = 0; i < len; i++)
{
uint8_t b = *((uint8_t *)buf + i);
crc = CRC32Table[b ^ (crc >> 24)] ^ (crc << 8);
}
return crc;
}
int main(int argc, char *argv[])
{
uint32_t crc;
CRC32_Init(1);
crc = CRC32_Calc("hello", 5);
printf("hello: %08Xn", crc);
}
很多单片机例如STM、NXP等都在硬件上实现了CRC计算引擎,上位机与其通信,如果有CRC32计算的话,需要统一两端的CRC32算法,网上找的一些我看都不靠谱,计算结果和单片机上的结果不一致,我贴一下我写的代码吧。
#include
#include
//{0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, ...}
//hello: E6CE9AC2
static uint32_t CRC32Table[256];
void CRC32_Init(int order)
{
uint32_t poly;
int i;
if(order)
poly = 0x4C11DB7;
else
poly = 0xEDB88320;
for(i = 0; i < 256; i++)
{
uint32_t crc = order ? i << 24 : i;
int j;
for (j = 0; j < 8; j++)
{
if(order)
{
crc = (crc & 0x80000000) ? (poly ^ (crc << 1)) : (crc << 1);
}
else
{
crc = (crc & 1) ? (poly ^ (crc >> 1)) : (crc >> 1);
}
}
CRC32Table = crc;
}
}
uint32_t CRC32_Calc(void *buf, int len)
{
uint32_t crc = -1;
int i;
for(i = 0; i < len; i++)
{
uint8_t b = *((uint8_t *)buf + i);
crc = CRC32Table[b ^ (crc >> 24)] ^ (crc << 8);
}
return crc;
}
int main(int argc, char *argv[])
{
uint32_t crc;
CRC32_Init(1);
crc = CRC32_Calc("hello", 5);
printf("hello: %08Xn", crc);
}
举报