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作为字节参数,以获得更快的生成代码.
你可以考虑使用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"作为参数,因此数组不会被复制两次.
不要忘记将代码页分配给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)