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.
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.
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.
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.
But what about a string? A string is composed of: An 8-byte object header (4-byte SyncBlock and a 4-byte type descriptor)
I ended up using
TEncoding.Unicode.GetString( MyByteArray );
StringOf converts TBytes to a UnicodeString. BytesOf converts a UnicodeString to TBytes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With