Thema: Delphi StringToHex (nonVCL)

Einzelnen Beitrag anzeigen

bigg
(Gast)

n/a Beiträge
 
#1

StringToHex (nonVCL)

  Alt 15. Okt 2004, 23:17
Mit der Funktion StringToHex() kann man einen String in die Hexschreibe umwandeln, wie es auch ein Hex-Editor normalerweise macht.
Delphi-Quellcode:
function StringToHex(Text: String): String;
var
  i, Number: Integer;
begin
  Result := '';

  for i := 1 to Length(Text) do
  begin
    Number := Ord(Text[i]);

    case Number div 16 of
      0: Result := Result + '0';
      1: Result := Result + '1';
      2: Result := Result + '2';
      3: Result := Result + '3';
      4: Result := Result + '4';
      5: Result := Result + '5';
      6: Result := Result + '6';
      7: Result := Result + '7';
      8: Result := Result + '8';
      9: Result := Result + '9';
      10: Result := Result + 'A';
      11: Result := Result + 'B';
      12: Result := Result + 'C';
      13: Result := Result + 'D';
      14: Result := Result + 'E';
      15: Result := Result + 'F';
    end;

    case Number mod 16 of
      0: Result := Result + '0';
      1: Result := Result + '1';
      2: Result := Result + '2';
      3: Result := Result + '3';
      4: Result := Result + '4';
      5: Result := Result + '5';
      6: Result := Result + '6';
      7: Result := Result + '7';
      8: Result := Result + '8';
      9: Result := Result + '9';
      10: Result := Result + 'A';
      11: Result := Result + 'B';
      12: Result := Result + 'C';
      13: Result := Result + 'D';
      14: Result := Result + 'E';
      15: Result := Result + 'F';
    end;
  end;
end;
Sprint hat diesen Code noch ein wenig verpackt und beschleunigt:
Delphi-Quellcode:
function StrToHex(const S: String): String;
const
  HexDigits: array[0..15] of Char = '0123456789ABCDEF';
var
  I: Integer;
  P1: PChar;
  P2: PChar;
  B: Byte;
begin

  SetLength(Result, Length(S) * 2);
  P1 := @S[1];
  P2 := @Result[1];

  for I := 1 to Length(S) do
  begin
    B := Byte(P1^);
    P2^ := HexDigits[B shr 4];
    Inc(P2);
    P2^ := HexDigits[B and $F];
    Inc(P1);
    Inc(P2);
  end; {end for}

end; {end function}
[edit=Chakotay1308]Beitrag vervollständigt. Mfg, Chakotay1308[/edit]
  Mit Zitat antworten Zitat