这几天在做一个上位机软件,和变频器的通讯用到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.
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.
解决方案 »
- 关于多个Tclientsocket 的onRead事件
- dephi如何使用combox?
- 局域网读取文件
- 大家来比较一下serverSokcet与clientSocket和idTcpServer与idTcpClient两组通讯组件的异同
- 再看看这段代码吧,该怎么改才能在Access正运行呢?请指教!
- 寻求这样的控件 http://www.queenball.com/hm/a1.gif
- Table的Active与close、open
- 新手请教,如何用TFindDialog进行查找?
- 这是什么毛病?BCD actual:Integer
- 程序运行出结果后,如何将之弹到最上面,以显示给用户,提醒用户?
- SQL语言查询出错(两个条件查询)
- 不能一起使用多个模糊查询判断吗?
var
xuchong:array[1..4]of byte;
begin
xuchong[1]:=byte($20);
xuchong[2]:=byte($00);
xuchong[3]:=byte($00);
xuchong[4]:=byte($01);
嘿嘿~~~太小白了 搞不懂很多基础了 回去要恶补了~
DELPHI的异或是什么: x xor y =x(非y)+(非x)y