您的位置:首页 > 编程语言 > Delphi

Delphi 常用进制转换及CRC校验、和校验

2017-12-07 16:33 309 查看
和校验部分为 http://download.csdn.net/download/andyshawchina/7080801  下载资源,在此感谢!可用于IEC101规约的和校验。

其他为自己整理收集。

CRC8部分DELPHI 代码为本人原创(https://wenku.baidu.com/view/e7ebb221bcd126fff7050b62.html),最早公布于2011年9月,

CSDN下载中的该资源为他人上传(http://download.csdn.net/download/as504615572as/6607677)。

function StrToHexStr(const S:string):string;

//字符串转换成16进制字符串

var

  I:Integer;

begin

  for I:=1 to Length(S) do

  begin

    if I=1 then

      Result:=IntToHex(Ord(S[1]),2)

    else Result:=Result+IntToHex(Ord(S[I]),2);

  end;

end;

function Hex2Dec(Hexs: string): string;

//十六进制转换成十进制

begin

 Result := IntToStr(StrToInt('$'+Hexs));

end;

function CRC8(Value: String): char;  //CDT 校验

var

    uchCRC: Byte;

    iDataLen,i: Integer;

    str:string;

    intHex:integer;

begin

    uchCRC := $0;

    Value:= StringReplace(Value,' ','',[rfReplaceAll]);  //去除空格

    iDataLen := Length(Value);

    for i:=1 to (iDataLen div 2) do

    begin

       str:=copy(Value,2*i-1,2);//顺序取2个字符

       intHex:= strtoint('$'+str); //转换为16进制,+$

       uchCRC := CRC8_TABLE[uchCRC XOR intHex];

    end;

    Result := Char(not uchCRC); //求反结果

end;

function HexStrToStr(const S: string): string;

  //16进制字符串转换成字符串

var

  t: Integer; 

  ts: string; 

  M, Code: Integer; 

begin 

  t := 1; 

  Result := ''; 

  while t <= Length(S) do 

  begin   // 2006.10.21

    while (t <= Length(S)) and (not (S[t] in ['0'..'9', 'A'..'F', 'a'..'f'])) do

      Inc(t);

    if (t + 1 > Length(S)) or (not (S[t + 1] in ['0'..'9', 'A'..'F', 'a'..'f'])) then 

      ts := '$' + S[t]

    else

      ts := '$' + S[t] + S[t + 1];

    Val(ts, M, Code);

    if Code = 0 then

      Result := Result + Chr(M);

    Inc(t, 2);

  end;

end;

function GetChecksum(AStr: string): string;  //和校验

var

  t,i,j: integer;

  strNo:string;

  AChar:Char;

begin

  t := 0;

  j := (length(AStr) div 3) ;

  if (length(AStr) mod 3)>0 then

     j:= j+1;

  for i:=1 to j do

  begin

    strNo:=Copy(AStr,(i-1)*3+1,2); // s[i]+s[i+1];

    strNo :=HexStrToStr(strNo);  // Hex -> Str

    AChar :=strNo[1];

    t := t + Ord(Byte(AChar));

  end;

  Result := RightStr(IntToHex(t,4),2);

end;

function BinToDec(Value:string):string;  //二进制转十进制

var

  str:string;

  i,int:Integer;

begin

  str :=UpperCase(Value);

  int := 0;

  for i := 1 to Length(str) do

   int := int * 2 + Ord(str[i]) - 48;

  Result := IntToStr(int);

end;  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  DELPHI 校验 进制 转换