程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> CRC32生成碼表方法實現

CRC32生成碼表方法實現

編輯:Delphi
   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;
  
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved