Delphi编程实现获取文件CRC32值

减小字体 增大字体 作者:佚名  来源:不详  发布时间:2010-11-17 14:35:05

参考如下代码:

Table:Array[0..255] of DWORD;

procedure MakeTable();
var
  i,j,Crc:integer;
begin
  for i:=0 to 255 do
    begin
      Crc:=i;
      for j:=0 to 7 do
        begin
          if (Crc and 1)<>0 then
            Crc:=(Crc shr 1) xor $EDB88320
          else
            Crc:=Crc shr 1;
        end;
      Table[i]:=Crc;
    end;
end;

procedure GetCRC32File(FileName:string;var CRC32:DWORD);
var
  F:file;
  BytesRead:DWORD;
  Buffer:array[1..65521] of Byte;
  i:Word;
begin
  FileMode :=0;
  CRC32 :=$ffffffff;
  {$I-}
  AssignFile(F,FileName);
  Reset(F,1);
  if IoResult = 0 then
    begin
      repeat
      BlockRead(F,Buffer,Sizeof(Buffer),BytesRead);
      for i := 1 to BytesRead do
        CRC32 := (CRC32 shr 8) xor Table[Buffer[i] xor (CRC32 and $000000ff)];
      until BytesRead = 0;
    end;
  CloseFile(F);
  {$I+}
  CRC32 := not CRC32;
end;
   
function GetCrc32Str(s: string; Seed: LongInt):string;
var
  Count: Integer;
  CrcVal: LongInt;
begin
  CrcVal := Seed;
  for Count := 1 to Length(s) do
    CrcVal := Table[Byte(CrcVal xor DWORD(Ord(s[Count])))] xor ((CrcVal shr 8) and $00FFFFFF);
  Result := IntToHex(not(CrcVal), 8);
end;

调用:
procedure TForm1.Button1Click(Sender: TObject);
begin
  MakeTable();
  Edit1.Text:=GetCrc32Str('11111111',8);//这里取指定字符串的CRC32校验值;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  FileStr:String;
  crc: DWORD; 
begin
  MakeTable();
  FileStr:=Application.ExeName;//这里取指定的文件的crc32校验值;
  GetCRC32File(FileStr,crc);
  if crc<>0 then
    Edit2.Text:=PChar(IntToHex(crc,6));
end;

Tags:

作者:佚名
  • 好的评价 如果您觉得此文章好,就请您
      100%(1)
  • 差的评价 如果您觉得此文章差,就请您
      0%(0)

文章评论评论内容只代表网友观点,与本站立场无关!

   评论摘要(共 0 条,得分 0 分,平均 0 分) 查看完整评论

广告位置B