How can I convert TBytes to RawByteString?

自闭症网瘾萝莉.ら 提交于 2019-12-05 00:35:33

问题


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;

回答1:


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.




回答2:


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.




回答3:


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;



回答4:


And remember to test:

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



来源:https://stackoverflow.com/questions/773297/how-can-i-convert-tbytes-to-rawbytestring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!