天天看点

Delphi两个有用的函数

function StrToHexStr(const s: string): string;
var
  i: Integer;
  vBuff: TBytes;
  AnSiStr: AnsiString;
begin
  Result := '';
  if s = '' then Exit;  
  vBuff := BytesOf(AnsiString(s));
  for I := 0 to Length(vBuff) - 1 do begin
    Result := Result  + System.SysUtils.IntToHex(vBuff[i], 2);
    if (Result <> '') and (i < Length(vBuff) - 1) then Result := Result + '|';
  end;
end;


function HexStrToStr(const s: string): string;
var
  i: Integer;
  vBuff: TBytes;
  vLst: TStringList;
begin
  Result := '';
  if s = '' then Exit;  
  vLst := TStringList.Create;
  try
    vLst.Delimiter := '|';
    vLst.DelimitedText := s;
    SetLength(vBuff, vLst.Count);
    for I := 0 to vLst.Count - 1 do begin
      vBuff[i] := StrToIntDef('$' + vLst.Strings[i], 0);
    end;
    Result := String(StringOf(vBuff));
  finally
    FreeAndNil(vLst);
  end;
end;