Scalabium Software

SMExport advertising
Knowledge for your independence'.
Home Delphi and C++Builder tips


#48: Algorithm of CRC32 calculation for file

If you need calculate a CRC32 for some file or some string, then you must do:
1. build a CRC table
2. calculate a CRC for each line of your file
3. calculate a total CRC

1. CRC table creation:

type
  Long = record
    LoWord: Word;
    HiWord: Word;
  end;

const
  CRCPOLY = $EDB88320;

var
  CRCTable: array[0..512] Of Longint;

procedure BuildCRCTable;
var
  i, j: Word;
  r: Longint;
begin
  FillChar(CRCTable, SizeOf(CRCTable), 0);
  for i := 0 to 255 do
  begin
    r := i shl 1;
    for j := 8 downto 0 do
      if (r and 1) <> 0 then
        r := (r Shr 1) xor CRCPOLY
      else
        r := r shr 1;
    CRCTable[i] := r;
   end;
end;

2. CRC calculation for file:

function RecountCRC(b: byte; CrcOld: Longint): Longint;
begin
  RecountCRC := CRCTable[byte(CrcOld xor Longint(b))] xor ((CrcOld shr 8) and $00FFFFFF)
end;

function HextW(w: Word): string;
const
  h: array[0..15] Of char = '0123456789ABCDEF';
begin
  HextW := '';
  HextW := h[Hi(w) shr 4] + h[Hi(w) and $F] + h[Lo(w) shr 4]+h[Lo(w) and $F];
end;

function HextL(l: Longint): string;
begin
  with Long(l) do
    HextL := HextW(HiWord) + HextW(LoWord);
end;

function GetCRC32(FileName: string): string;
var
  Buffer: PChar;
  f: File of Byte;
  b: array[0..255] of Byte;
  CRC: Longint;
  e, i: Integer;
begin
  BuildCRCTable;
  CRC := $FFFFFFFF;
  AssignFile(F, FileName);
  FileMode := 0;
  Reset(F);
  GetMem(Buffer, SizeOf(B));
  repeat
    FillChar(b, SizeOf(b), 0);
    BlockRead(F, b, SizeOf(b), e);
    for i := 0 to (e-1) do
     CRC := RecountCRC(b[i], CRC);
  until (e < 255) or (IOresult <> 0);
  FreeMem(Buffer, SizeOf(B));
  CloseFile(F);
  CRC := Not CRC;
  Result := '$' + HextL(CRC);
end;


Published: November 30, 1999

See also
 
ABA Spreadsheet Convert
Word Web-stream
Protected Storage Viewer
Paradox to Text converter
DBISAM Viewer
ABA Picture Convert
SMMsg suite
Paradox Password Recovery
Paradox ActiveX
ABA Document Convert
 
 


Contact to webmaster

 

Borland Software Code Gear Scalabium Delphi tips

Copyright© 1998-2021, Scalabium Software. All rights reserved.
webmaster@scalabium.com

SMExport/SMImport suites