这几天在做一个上位机软件,和变频器的通讯用到CRC16校验。说明书上给的是C语言的代码,改成Delphi怎么都不对,算出来的校验值不正确。把代码贴出来给大家看看,还请高手赐教。 我感觉是P^这个指针取得数值不对 感觉取不到变量的值,另:如何让16位的数据分8位8位的进行校验?
unit Unit1;interfaceuses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;type
  PBYTE=^BYTE;
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
  function CRC16(const pData:Pointer;nLength:Integer):Word;
var
  Form1: TForm1;implementation{$R *.dfm}function CRC16(const pData:Pointer;nLength:Integer):Word;
var
crc_value,i,test:integer;
p:PBYTE;
begin
  crc_value:=$ffff;
  p:=PBYTE(pData);
  while ((nLength)<>0) do
  begin
    crc_value:=crc_value xor p^;
    Inc(p);
    for i:=1 to 8 do
    begin
      if((crc_value and $0001) <> 0 ) then
        crc_value:=(crc_value shr 1) xor $a001
      else
        crc_value:=(crc_value shr 1);
    end;
    Dec(nLength);
  end;
  result:=crc_value;
end;procedure TForm1.Button1Click(Sender: TObject);
var
xuchong:integer;
begin
xuchong:=$2000; //CA24
form1.Edit1.Text:=inttohex(CRC16(@xuchong,2),4);
end;end.

解决方案 »

  1.   

    貌似解决了 我把数据放入了个数组~~就可以了 ~~
    var
    xuchong:array[1..4]of byte;
    begin
    xuchong[1]:=byte($20);
    xuchong[2]:=byte($00);
    xuchong[3]:=byte($00);
    xuchong[4]:=byte($01);
    嘿嘿~~~太小白了 搞不懂很多基础了 回去要恶补了~
      

  2.   

    这是MODBUS串行通讯的校验码子程序,  ^是异或运算(XOR),不是取指针!!
    DELPHI的异或是什么:  x xor y =x(非y)+(非x)y
      

  3.   

    1^1=0   1^0=1  0^0=0  0^1=1    这就是异或运算(xor)