单片机开发过程中,驱动通信的开发都会涉及到,而在数据通信的过程中,存在各种各样的校验方式,普通的累加和,累加异或等校验方式都可以粗粒度的对数据进行验证。但是在可靠性略高一些的通信过程中使用CRC32的频率会高很多,例如flash的写入,高频率高带宽的数据传输等,下面列举出来单片机的通用CRC32校验,以STM32平台为例,可适用于任何平台任何场景,亲测可用。
#include <stdio.h>
unsigned long CrcGen_STM32(unsigned long data[], unsigned long size);
int main(void)
{
uint8_t data[28] = {0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00};
unsigned long crcresult = 0;
crcresult = CrcGen_STM32((unsigned long *)data,7);
return 0;
}
unsigned long CrcGen_STM32(unsigned long data[], unsigned long size)
{
unsigned long i,j,temp,crc = 0xFFFFFFFF;
for(i=0; i<size; i++)
{
temp = data[i];
for(j=0; j<32; j++)
{
if( (crc ^ temp