求用delphi编写的LRC校验位算法函数,急!!!

求用delphi编写的LRC校验位算法函数,急!!!

  某命令串为":010200000001FC"

  其16进制为“3A 30 31 30 32 30 30 30 30 30 30 30 31 46 43 0D 0A”。其中第一个为起始符,2-13为数据,14-15即“FC”为LRC校验码,有人能写一个取得校验位的函数吗?

下边有一段用VC写的程序 将帧的内容,除去头代码,用十六进制表示,求和,模FF,然后取补码,以ASCII码表示即可。

  例如:ASCII帧

   3A 30 31 30 32 30 30 30 30 30 30 30 31 46 43 0D 0A

  将校验内容用十六进制表示为:

   00 01 00 02 00 00 00 00 00 00 00 01

  将以上数值用十六进制求和,模FF:

   00+01+00+02+00+00+00+00+00+00+00+01=04=0000 0100

  取反:1111 1011

  加1: 1111 1100

  十六进制变换:F C

  ASCII码:46 43

  LRC就是这样算出来的这里有一段用C写的程序,有谁能用DELPHI写吗?

static unsigned char LRC(auchMsg,usDataLen)

  

  unsigned char *auchMsg ; /* 要进行计算的消息 */

  

  unsigned short usDataLen ; /* LRC 要处理的字节的数量*/

  

  { unsigned char uchLRC = 0 ; /* LRC 字节初始化 */

  

  while (usDataLen--) /* 传送消息 */

  

  uchLRC += *auchMsg++ ; /* 累加*/

  

  return ((unsigned char)(-((char_uchLRC))) ;

  

  }

解决方案 »

cvm

function GetLRC(AData: array of Byte; iLen: Integer): Byte;

var

iLoop : Integer;

begin

Result := 0;

for iLoop := 0 to iLen - 1 do Result := Result + AData[iLoop];

Result := Result xor $FF + 1;

end;procedure TForm1.FormCreate(Sender: TObject);

var

AData: array[0..5] of Byte;

iLRC : Byte;

begin

AData[0] := $01;

AData[1] := $02;

AData[2] := $00;

AData[3] := $00;

AData[4] := $00;

AData[5] := $01;

iLRC := GetLRC(AData, 6);

ShowMessage(IntToHex(iLRC,2));

end;

再多加个函数,可以直接获取类似楼主例子中的"010200000001FC"这个字符串:

function GetLRC(AData: array of Byte; iLen: Integer): Byte;

var

iLoop : Integer;

begin

Result := 0;

for iLoop := 0 to iLen - 1 do Result := Result + AData[iLoop];

Result := Result xor $FF + 1;

end;function GetHexString(AData: array of Byte; iLen: Integer): String;

var

iLoop: Integer;

begin

Result := '';

for iLoop := 0 to iLen - 1 do

Result := Result + IntToHex(AData[iLoop], 2);

Result := Result + IntToHex(GetLRC(AData, iLen), 2);

end;procedure TForm1.FormCreate(Sender: TObject);

var

AData: array[0..5] of Byte;

begin

AData[0] := $01;

AData[1] := $02;

AData[2] := $00;

AData[3] := $00;

AData[4] := $00;

AData[5] := $01;

ShowMessage(GetHexString(AData, 6));

end;

static byte LRC(byte[] data)

{

byte lrc = 0;

foreach (byte c in data)

{

lrc += c;

}

return (byte)-lrc;

}