计算ModBus CRC 校验码(delphi实现)

真后悔当初网络课没好好学,最近在编一个程序遇到一个CRC校验码的计算,左看右看,以前没有接触过这方面的编程,没办法,还好找了一大堆文字叙述的材料,终于搞定了.­

我的CRC的多项式是以ModBus 的A001(1010 0000 0000 0001) ­

nit Unit1; ­

interface ­

uses ­

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, ­

  Dialogs, StdCtrls; ­

type ­

  TForm1 = class(TForm) ­

    Button1: TButton; ­

    Edit1: TEdit; ­

    Label3: TLabel; ­

    Edit2: TEdit; ­

    procedure Button1Click(Sender: TObject); ­

  private ­

    { Private declarations } ­

  public ­

    { Public declarations } ­

  end; ­

var ­

  Form1: TForm1; ­

implementation ­

{$R *.dfm} ­

function GetCRC16CheckCode(S: String): Word; ­

const ­

  CRCPolynomial=$A001;//ModBus CRC 校验码:多项式:A001(1010 0000 0000 0001)进行异或 ­

var ­

  LSBNoZero: Boolean; ­

  Idx, i: Integer; ­

begin ­

  Result:=$FFFF; ­

  for Idx:=1 to Length(S) do ­

    begin ­

    Result:= Ord(S[Idx]) xor Result; ­

    for i:=1 to 8 do ­

      begin ­

      LSBNoZero:=Result and $0001<>0; ­

      Result:=Result shr 1; ­

      if LSBNoZero then ­

        begin ­

        Result:=Result xor CRCPolynomial; ­

        end; ­

      end; ­

    end; ­

end; ­

procedure TForm1.Button1Click(Sender: TObject); ­

var ­

  Data: String; ­

  DataLen, i: Integer; ­

begin ­

  DataLen:=Length(Edit1.Text) div 2 ; ­

  SetLength(Data, DataLen); ­

  for i:=1 to DataLen do ­

    begin ­

    Data[i]:=Chr(StrToInt('$'+Copy(Edit1.Text, (i-1)*2+1, 2))); ­

    end; ­

  Edit2.Text:=IntToHex(GetCRC16CheckCode(Data), 4); ­

end; ­

end.­

你可能感兴趣的:(DELPHI,delphi,integer,button,string,forms,interface)