[fpc-pascal] old school crc32

wkitty42 at windstream.net wkitty42 at windstream.net
Sun Jul 24 01:18:12 CEST 2016

this is driving me battier than i already am :(

i have a binary file that contains a record of data... the first field of the 
data is a crc32 value of a string of characters... the string of characters is 
lower cased before being fed to the crc32 function... i need to calculate the 
same crc32 value as what is stored in the file...

i've already checked the polynomial ($edb88320) is the same in both, the 
original implementation (converted to TP4 in 1988) and this implementation...

the original routine uses longint and speaks of initializing the variable to 
$ffffffff before feeding it to the crc32 routine... the existing routine in FPC 
says "Pre- and post-conditioning (one's complement) is performed within this 
function so it shouldn't be done by the application." but that doesn't give me 
the proper answer in this case... i've tried using cardinal types and longint 
types to no avail...

the following is so so so very close but now i'm bald headed, completely lost in 
the deep dark woods and can't find my breadcrumbs any more :(

program damncrc32;


   crc, sysutils;

   mystring : pchar = 'aaaaaaaa aaaaaaaa';
   // desired crc32 checksum value 0xd728cba6
   // crc32 as seen in binary file 0xcba6d728
//  mystrsum : cardinal = 3609775014; // crc32 in decimal
   mystrsum : longint = -685192282; // crc32 in decimal

//  mycrc32 : cardinal;
   mycrc32 : longint;
   mystrln : longint;
   counter : longint;

   // set the string length - subtract 1 later!
   mystrln := length(mystring);

   // prime the crc32 variable
   mycrc32 := crc32(0, nil, 0);
//  mycrc32 := $ffffffff;
//  mycrc32 := -1;

   // now calculate the crc32 of the string
   for counter := 0 to mystrln-1 do
       mycrc32 := crc32(mycrc32, @mystring[counter], 1);
       writeln('mystring[',inttostr(counter),'] : ',mystring[counter],' 

   // write the string and its length
   writeln('mystring : ',mystring,'  length : ',mystrln);

   // write the desired crc32 in decimal, hex and inverted hex
   writeln('  desired crc32 : ',mystrsum:12,'  (normal 0x',hexstr(mystrsum,8),' 
- inverted 0x',hexstr(swap(mystrsum),8),')');

   // write the result crc32 in decimal, hex and inverted hex
   writeln('   result crc32 : ',mycrc32:12,'  (normal 0x',hexstr(mycrc32,8),' - 
inverted 0x',hexstr(swap(mycrc32),8),')');

   // did we get it right???
   write('crc32 checksum');
   if mycrc32 <> mystrsum then
     writeln(' DOES NOT match.')
     writeln(' matches! YAY!!!');

More information about the fpc-pascal mailing list