calculating and using the CRC-32

disclaimer

the CRC-32 is used to protect long messages from bit errors.
For the CRC-16 which protects up too 2^16 bits, or 8k bytes, see CRC-16 in Delphi

the h file

//----------------------------------------
#ifndef crc32H
#define crc32H
//----------------------------------------
DWORD   crc32table[512];

void    buildcrc32table();

int calc_crc32(char * buffer, int size);

#endif

the cpp file

//---------------------------------------
#include 
#pragma hdrstop

#include "crc32.h"

//---------------------------------------
#pragma package(smart_init)

void    buildcrc32table()
{
 const  DWORD crcpoly=0xEDB88320;
 WORD   i,j;
 DWORD  r;

 for (i=0;i<512;i++) crc32table[i]=0;

 for (i=0;i<=255;i++)
 { r = (i << 1);
   for (j=8; j>0; j--)
   { if ((r & 1)!=0)
     { r= (r>>1)^crcpoly;}
     else { r = (r >>1); }
   }
   crc32table[i]=r;
  }
}

int calc_crc32(char * buffer, int size)
{
 int  u,h,tcrc;
 int i;

 tcrc=0xFFFFFFFF;
 for (i=0;i<=(size-1);i++)
 { u=buffer[i];         // one byte signextend
   h=crc32table[(byte)(u ^ tcrc)] ^ ((tcrc>>8) & 0x00FFFFFF);
   tcrc=h;
 }
 return -h;
}

usage

the following shows a sample application where a message is stored in TxMsgBuffer with the size TxSize.

..
buildcrc32table(); // required once
..

unsigned char TxMsgBuffer[6000];
int TxSize;

void DSPCommSend()
{
 int i;
 unsigned char LenLo, LenHi;
 unsigned char CRC_1,CRC_2,CRC_3,CRC_4;
 WORD    Len;
 unsigned int CRC;

 LenLo=(TxSize & 0xFF);
 LenHi=((TxSize & 0xFF00)>>8);
 TxMsgBuffer[0]=SYN;
 TxMsgBuffer[1]=SYN;
 TxMsgBuffer[2]=SYN;
 TxMsgBuffer[3]=SYN;
 TxMsgBuffer[4]=STX;
 TxMsgBuffer[5]=LenLo;
 TxMsgBuffer[6]=LenHi;
 for (i=0;i>8);
 CRC_3=((CRC & 0xFF0000)>>16);
 CRC_4=((CRC & 0xFF000000)>>24);
 TxMsgBuffer[TxSize+7]=CRC_1;
 TxMsgBuffer[TxSize+8]=CRC_2;
 TxMsgBuffer[TxSize+9]=CRC_3;
 TxMsgBuffer[TxSize+10]=CRC_4;
 // Sendmessage(TxMsgBuffer,TxSize+10);
 ...
}



my BCB
home

last updated: 28.june.01

Copyright (99,2001) Ing.Büro R.Tschaggelar