tags:

views:

122

answers:

4

I developed the following function to convert strings to hex values.

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; 

Now I was wondering whether there is a more efficient way to convert the strings?

+1  A: 

It seems good enough, you could always have a byte->2 hex digits lookup table, but that (and similar optimizations) seems like overkill to me in most cases.

Ofir
+1  A: 

Try this one

   function String2Hex(const Buffer: Ansistring): string;
   var
     n: Integer;
   begin
     Result := '';
     for n := 1 to Length(Buffer) do
       Result := LowerCase(Result + IntToHex(Ord(Buffer[n]), 2));
   end;
Bharat
Great! I just made a performance test and your function is even faster (just a little) than mine. Thanks!
Forlan07
@Bharat: How often do you need to lower-case a string until you can be sure that it really worked?
mghie
@Forlan07, do your tests again. The code in this sample re-allocates Result once for every char in "Buffer", uses IntToHex to turn numbers into hex... it can't possibly be faster! Your code only allocates memory once, and then does a single for loop over the text to turn it all into hex.
Cosmin Prund
@Cosmin Prund: You are right... It seems as if there is a bug in one of my functions where I take the time. I just used a different function to take the time.
Forlan07
+5  A: 

Depending on your Delphi version:

D5-D2007

uses classes;
function String2Hex(const Buffer: Ansistring): string;
begin
  SetLength(result, 2*Length(Buffer));
  BinToHex(@Buffer[1], @result[1], Length(Buffer));
end;

D2009+

uses classes;
function String2Hex(const Buffer: Ansistring): string;
begin
  SetLength(result, 2*Length(Buffer));
  BinToHex(@Buffer[1], PWideChar(@result[1]), Length(Buffer));
end;
Uwe Raabe
A: 

// StrToInt('$' + MyString); Oops, did not read the question very good...

Erik