如何将TBytes转换为RawByteString?

mjn*_*mjn 5 delphi string delphi-2009

在Delphi 2009中将声明为TBytes的字节数组转换为RawByteString的最佳方法是什么?这段代码实际上有效,也许有更快的方式(没有循环):

   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;
Run Code Online (Sandbox Code Playgroud)

A.B*_*hez 13

最好的方法是:

function Convert(const Bytes: TBytes): RawByteString; inline;
begin
  SetString(Result, PAnsiChar(pointer(Bytes)), length(Bytes));
end;
Run Code Online (Sandbox Code Playgroud)

并且不要忘记使用const作为字节参数,以获得更快的生成代码.


Ste*_*nas 6

你可以考虑使用move(未经测试)

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

并使用"const"作为参数,因此数组不会被复制两次.


Rem*_*eau 6

不要忘记将代码页分配给RawByteString数据,以便在将字符数据分配给任何其他String类型时正确转换字符数据:

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

  • @blerontin `RawByteString` 在*编译时*缺少字符集,但它继承了分配给它的任何字符串的*运行时*字符集。字节数组有一个隐含的字符集,即使字节有效负载本身没有携带该字符集。正如我在回答中所说,“RawByteString”可以分配给其他字符串类型,因此它需要在其有效负载中携带有效的字符集,以方便正确分配以避免数据丢失 (3认同)

Hea*_*are 5

并记得测试:

IF长度(字节)> 0 THEN MOVE .....