mjn
mjn

Reputation: 36684

How can I convert TBytes to RawByteString?

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;

Upvotes: 7

Views: 10658

Answers (4)

Remy Lebeau
Remy Lebeau

Reputation: 598424

The easiest way to convert bytes to a RawByteString is to use SetString().

Also, to avoid data loss if the RawByteString is ever assigned to other String types, you should assign a codepage to the RawByteString so that its character data gets converted correctly to the charset of the receiving String:

function Convert(const Bytes: TBytes): RawByteString; 
begin
  SetString(Result, PAnsiChar(PByte(Bytes))^, Length(Bytes));
  SetCodePage(Result, ..., False);
end;

Upvotes: 7

A.Bouchez
A.Bouchez

Reputation: 406

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.

Upvotes: 17

Steffen Binas
Steffen Binas

Reputation: 1488

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.

Upvotes: 7

HeartWare
HeartWare

Reputation: 8261

And remember to test:

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

Upvotes: 5

Related Questions