在Delphi中实现HexToStr函数和StrToHex函数

function TransChar(AChar: Char): Integer;
begin
  if AChar in ['0'..'9'] then
  Result := Ord(AChar) - Ord('0')
  else
  Result := 10 + Ord(AChar) - Ord('A');
end;
function StrToHex(AStr: string): string;
var
  I ,Len: Integer;
  s:char;
begin
  len:=length(AStr);
  Result:='';
  for i:=1 to len  do
  begin
    s:=AStr[i];
    Result:=Result +' '+IntToHex(Ord(s),2); //将字符串转化为16进制字符串,
                                            //并以空格间隔。
  end;
  Delete(Result,1,1); //删去字符串中第一个空格
end;
function HexToStr(AStr: string): string;
var
  I,len : Integer;
  CharValue: Word;
  Tmp:string;
  s:char;
begin
  Tmp:='';
  len:=length(Astr);
  for i:=1 to len  do
  begin
    s:=Astr[i];
    if s <> ' ' then Tmp:=Tmp+ string(s);
  end;
  Result := '';
  For I := 1 to Trunc(Length(Tmp)/2) do
  begin
    Result := Result + ' ';
    CharValue := TransChar(Tmp[2*I-1])*16 + TransChar(Tmp[2*I]);
    if (charvalue < 32) or (charvalue > 126)  then Result[I] := '.'   //非可见字符填充
    else Result[I] := Char(CharValue);
  end;
end;

 

posted @ 2015-06-18 23:05  tc310  阅读(1992)  评论(0编辑  收藏  举报