可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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;