9

What is the best way to convert an array of bytes declared as TBytes to a unicode string in Delphi 2009? In my particular case, the TBytes array has UTF-16 encoded data already (2 bytes for each char).

Since TBytes doesn't store a null terminator, the following will only work if the array happens to have #0 in the memory adjacent to it.

MyString := string( myBytes );

If not, the string result will have random data at the end (it could also probably cause a read violation depending on how long it took to encounter a #0 in memory).

If I use the ToBytes function, it returns 't'#0'e'#0's'#0't'#0, which is not what I want.

3 Answers 3

18

I ended up using

TEncoding.Unicode.GetString( MyByteArray );
12

StringOf converts TBytes to a UnicodeString. BytesOf converts a UnicodeString to TBytes.

2
  • Thanks Bruce, I revised my original question as it wasn't specific enough. The TBytes array is encoded as utf16 data, so ToBytes doesn't work. Nov 3, 2008 at 21:07
  • 1
    Sweet. As simple as 8 characters: StringOf :) Apr 23, 2015 at 10:50
4

If your TBytes contains UTF-16 characters, look at WideStringOf and WideBytesOf.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.