How to convert AnsiString to TBytes and vice versa?

6.6k Views Asked by At

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

2

There are 2 best solutions below

27
David Heffernan On BEST ANSWER

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));
7
Sebastian Z On

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;