Delphi tip#48: CRC32 calculation
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:
typeLong = recordLoWord: Word; HiWord: Word; end; constCRCPOLY = $EDB88320; varCRCTable: array[0..512] OfLongint; procedureBuildCRCTable; vari, j: Word; r: Longint; beginFillChar(CRCTable, SizeOf(CRCTable), 0); fori := 0 to255 do
beginr := i shl1; forj := 8 downto0 do
if(r and1) <> 0 thenr := (r Shr1) xorCRCPOLY elser := r shr1; CRCTable[i] := r; end; end;
2. CRC calculation for file:
functionRecountCRC(b: byte; CrcOld: Longint): Longint; beginRecountCRC := CRCTable[byte(CrcOld xorLongint(b))] xor((CrcOld shr8) and$00FFFFFF) end; functionHextW(w: Word): string; consth: array[0..15] Ofchar = '0123456789ABCDEF'; beginHextW := ''; HextW := h[Hi(w) shr4] + h[Hi(w) and$F] + h[Lo(w) shr4]+h[Lo(w) and$F]; end; functionHextL(l: Longint): string; begin
withLong(l) doHextL := HextW(HiWord) + HextW(LoWord); end; functionGetCRC32(FileName: string): string; varBuffer: PChar; f: File ofByte; b: array[0..255] ofByte; CRC: Longint; e, i: Integer; beginBuildCRCTable; CRC := $FFFFFFFF; AssignFile(F, FileName); FileMode := 0; Reset(F); GetMem(Buffer, SizeOf(B)); repeatFillChar(b, SizeOf(b), 0); BlockRead(F, b, SizeOf(b), e); fori := 0 to(e-1) doCRC := RecountCRC(b[i], CRC); until(e < 255) or(IOresult <> 0); FreeMem(Buffer, SizeOf(B)); CloseFile(F); CRC := NotCRC; Result := '$' + HextL(CRC); end;
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。