Search code examples
arraysdelphitype-conversiondelphi-xe6tstringlist

Delphi (XE6) : Array of Byte to TStringList


I have a function which returns a dynamic array of byte

type
  TMyEncrypt = Array of Byte;
  TMyDecrypt = Array of Byte;

function decrypt(original: TMyEncrypt) : TMyDecrypt;

The content of the returned dynamic array TMyDecrypt is a standard text with CRLF.

How can i load this into a TStringList with CRLF as separator, without saving it to a temporary file before?

EDIT: the retruned array of byte contains unicode coded characters


Solution

  • Decode the byte array to a string, and then assign to the Text property of the string list.

    var
      Bytes: TBytes;
      StringList: TStringList;
    ....
    StringList.Text := TEncoding.Unicode.GetString(Bytes);
    

    Note the use of TBytes which is the standard type used to hold dynamic arrays of bytes. For compatibility reasons it makes sense to use TBytes. That way your data can be processed by other RTL and library code. A fact we immediately take advantage of by using TEncoding.

    You could use SetString, as my answer originally suggested:

    var
      Text: string;
      Bytes: TBytes;
      StringList: TStringList;
    ....
    SetString(Text, PChar(Bytes), Length(Bytes) div SizeOf(Char)));
    StringList.Text := Text;
    

    Personally I prefer to use TEncoding because it is very explicit about the encoding being used.

    If your text was null terminated then you could use:

    StringList.Text := PChar(Bytes);
    

    Again, I'd prefer to be explicit about the encoding. And I might be a little paranoid about my data somehow not being null terminated.

    You might find that UTF-8 is a more efficient representation than UTF-16.