views:

1076

answers:

4

What is the best way to convert an array of bytes declared as TBytes to a RawByteString in Delphi 2009? This code actually works, maybe there is a faster way (without loop):

   function Convert(Bytes: TBytes): RawByteString; 
   var
     I: Integer;
   begin
     SetLength(Result, Length(Bytes));
     for I := 0 to ABytes - 1 do
       Result[I + 1] := AnsiChar(Bytes[I]);
   end;
+5  A: 

You could consider using move (untested)

function Convert(const Bytes: TBytes): RawByteString; 
begin
  SetLength(Result, Length(Bytes));
  Move(Bytes[0], Result[1], Length(Bytes))  
end;

And use "const" for the parameter so the array is not copied twice.

Stebi
Works like a charm, thank you!
mjustin
+4  A: 

And remember to test:

IF Length(Bytes)>0 THEN MOVE.....

HeartWare
+3  A: 

Don't forget to assign a codepage to the RawByteString data so that the character data gets converted correctly if it is ever assigned to any other String type:

function Convert(const Bytes: TBytes): RawByteString; 
begin
  SetLength(Result, Length(Bytes));
  if Length(Bytes) > 0 then
  begin
    Move(Bytes[0], Result[1], Length(Bytes));
    SetCodePage(Result, ..., False);
  end;
end;
Remy Lebeau - TeamB
+2  A: 

The best way is this:

function Convert(const Bytes: TBytes): RawByteString; inline;
begin
  SetString(Result, PAnsiChar(pointer(Bytes)), length(Bytes));
end;

And don't forget to use const for Bytes parameters, for somewhat faster generated code.

A.Bouchez