String
是一个8位AnsiString
在 Delphi 7 中。只需分配TBytes
to the Length()
字符串和Move()
将字符串内容写入其中:
function AnsiBytesOf(const S: AnsiString): TBytes;
begin
SetLength(Result, Length(S) * SizeOf(AnsiChar));
Move(PChar(S)^, PByte(Result)^, Length(Result));
end;
如果你想成为政治正确并匹配什么TEncoding.GetBytes()
确实,你必须转换String
to a WideString
然后使用Win32 APIWideCharToMultiBytes()
函数将其转换为字节:
function AnsiBytesOf(const S: WideString): TBytes;
var
Len: Integer;
begin
Result := nil;
if S = '' then Exit;
Len := WideCharToMultiByte(0, 0, PWideChar(S), Length(S), nil, 0, nil, nil);
if Len = 0 then RaiseLastOSError;
SetLength(Result, Len+1);
WideCharToMultiByte(0, 0, PWideChar(S), Length(S), PAnsiChar(PByte(Result)), Len, nil, nil);
Result[Len] = $0;
end;