Search code examples
delphidata-conversionansistring

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 ?


Solution

  • 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));