﻿ 教你一招：CRC算法的實現_電腦知識網

# 教你一招：CRC算法的實現

2013-11-23 17:29:19  來源: Delphi編程
uses
WindowsSysUtilsClasses;

const　//Crc
Table:Array[] of DWORD=
( \$　\$ \$EEEC \$BA
\$DC \$AFF \$EA \$EA
\$EDB \$DCBA \$EDEE \$DD
\$BCB \$EBCBD \$EBD \$BFD
\$DB \$ABF \$FB \$BEDE
\$C \$BAC \$FDFA \$ACEC
\$CF \$CD \$FAFD \$DDF
\$BEC \$CE \$DE \$A
\$CED \$BD \$DDFD \$AABB
\$BAFA \$BC \$DBBBCD \$ACBCF
\$DCE \$DFC \$DCDDCF \$ABDD
\$DAC \$DEA \$CD \$BFD
\$BFB \$BC \$CFBA \$BBDAF
\$BE \$F \$CCDB \$BBE
\$FFC \$C \$CDAB \$BDD
\$DC \$DB \$DBC \$EFDA
\$B \$BBF \$FBFEA \$EBD
\$CA \$FF \$AE \$EE
\$BBF \$CC \$D \$FE
\$CED \$BAB \$FC \$FFC
\$BDC \$BE \$BBEBEA \$FCBC
\$DB \$ABCE \$ABC \$DBBE
\$D \$DE \$AAACF \$DDDCC
\$C \$AA \$BEB \$CC
\$B \$FB \$BD \$CEEF
\$EDEFE \$DC \$BD \$CDAB
\$EDB \$ABFBB \$BEC \$BDA
\$EB \$B \$DDAE \$AAAA
\$EECFB \$FFD \$AAE \$DEB
\$FD \$CB \$C \$EBE
\$FEDB \$DBE \$DAAA \$DDACC
\$FBDFF \$EBEEFF \$BBE \$BED
\$DBBF \$ABC \$FBDD \$BB
\$DDBDA \$AFABC \$AF \$A
\$CBBC \$BCA \$FDA \$E
\$CCC \$BBB \$B \$F
\$CBABBE \$BBDB \$BBA \$CBA
\$CDFFA \$BDCF \$CDEB \$BDEAED
\$BCB \$ECF \$AAC \$DA
\$CA \$EBEF \$ \$
\$BFA \$EBA \$BBBAE \$CBB
\$DEB \$EDBED \$CDCEFB \$BDBDF
\$DDD \$FDE \$DDBF \$FDAE
\$BECD \$FBB \$FBE \$B
\$AE \$FFFA \$BCA \$BC
\$FEFF \$FAE \$BFFD \$CCF
\$AAE \$DDDEE \$E \$BC
\$A \$DF \$D \$EEDB
\$ABCAE \$DEBBEC \$BCFF \$BFFE
\$BDBDFC \$CABACA \$B \$BAA
\$BAE \$CAB \$DB \$AFB

procedure GetCRCFile(FileName:string;var CRC:DWORD);
function GetCrcStr(s: string; Seed: LongInt):string;

implementation

procedure GetCRCFile(FileName:string;var CRC:DWORD);
var
F:file;
Buffer:array[] of Byte;
i:Word;
begin
FileMode :=;
CRC :=\$ffffffff;
{\$I}
AssignFile(FFileName);
Reset(F);
if IoResult = then
begin
repeat
for i := to BytesRead do
CRC := (CRC shr ) xor Table[Buffer[i] xor (CRC and \$ff)];
end;
CloseFile(F);
{\$I+}
CRC := not CRC;
end;

function GetCrcStr(s: string; Seed: LongInt):string;
var
Count: Integer;
CrcVal: LongInt;
begin
CrcVal := Seed;
for Count := to Length(s) do
CrcVal := Table[Byte(CrcVal xor DWORD(Ord(s[Count])))] xor ((CrcVal shr ) and \$FFFFFF);
Result := IntToHex(not(CrcVal) );
end;

end

調用
uses Crc;

procedure TFormButtonClick(Sender: TObject);
begin
EditText:=GetCrcStr();//這裡取指定字符串的CRC校驗值;
end;

procedure TFormButtonClick(Sender: TObject);
var
FileStr:String;
crc: DWORD;
begin
FileStr:=ApplicationExeName;//這裡取指定的文件的crc校驗值;
GetCRCFile(FileStrcrc);
if crc<> then
EditText:=PChar(IntToHex(crc));
end;
From:http://tw.wingwit.com/Article/program/Delphi/201311/24674.html