How can I convert TBytes to RawByteString?

匿名 (未验证) 提交于 2019-12-03 03:02:02

问题:

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:

And remember to test:

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



回答4:

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; 


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