zeus
zeus

Reputation: 13345

How to convert AnsiString to TBytes and vice versa?

I have an AnsiString and I need to convert it in the most efficient way to a TBytes. How can I do that ?

Upvotes: 4

Views: 7375

Answers (2)

Sebastian Z
Sebastian Z

Reputation: 4730

The function BytesOf converts an AnsiString to TBytes.

var
  A: AnsiString;
  B: TBytes;
begin
  A := 'Test';
  B := BytesOf(A);

  // convert it back
  SetString(A, PAnsiChar(B), Length(B));
end;

Upvotes: 11

David Heffernan
David Heffernan

Reputation: 612884

Assuming you want to retain the same encoding you can do this

SetLength(bytes, Length(ansiStr));
Move(Pointer(ansiStr)^, Pointer(bytes)^, Length(ansiStr));

In reverse it goes

SetLength(ansiStr, Length(bytes));
Move(Pointer(bytes)^, Pointer(ansiStr)^, Length(bytes));

Upvotes: 7

Related Questions