Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to convert TBytes (UTF-16) to a string?

Tags:

unicode

delphi

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.

like image 383
Jeremy Mullin Avatar asked Nov 03 '08 20:11

Jeremy Mullin


People also ask

How do you convert bytes to strings?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.

Is UTF-16 better than UTF-8?

UTF-16 is only more efficient than UTF-8 on some non-English websites. If a website uses a language with characters farther back in the Unicode library, UTF-8 will encode all characters as four bytes, whereas UTF-16 might encode many of the same characters as only two bytes.

How many bytes is UTF-16?

Likewise, UTF-16 is based on 16-bit code units. Therefore, each character can be 16 bits (2 bytes) or 32 bits (4 bytes). All UTFs include the full Unicode character repertoire , or set of characters.

How many bytes is a string?

But what about a string? A string is composed of: An 8-byte object header (4-byte SyncBlock and a 4-byte type descriptor)


2 Answers

I ended up using

TEncoding.Unicode.GetString( MyByteArray );
like image 185
Jeremy Mullin Avatar answered Oct 07 '22 04:10

Jeremy Mullin


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

like image 32
Bruce McGee Avatar answered Oct 07 '22 03:10

Bruce McGee