Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert TByteDynArray to string

Tags:

delphi

I'm working with web service and I have a problem with an invalid character was found in text content. I don't have much experience with encoding so I decided to pass the data as TByteDynArray. Here is the code I use from this answer.

class function StringHelper.StringToByteArray(value: string): TByteDynArray;
begin   
  SetLength(Result, Length(value) * SizeOf(Char));    
  if Length(value) > 0 then
  begin
    Move(value[1], Result[0], Length(value) * SizeOf(Char));
  end;
end;

I had success with converting string to TByteDynArray, but I don't know how to convert it back from TByteDynArray to string.

like image 927
Ago Avatar asked Jan 27 '23 13:01

Ago


1 Answers

Rather than copying the raw UTF16 bytes it is generally preferable to use the TEncoding class to perform such operations. And you might take this opportunity to become a little more proficient in text encodings.

So, you can use

bytes := TEncoding.UTF8.GetBytes(str);

to obtain the text as UTF8 encoded bytes.

In the opposite direction use

str := TEncoding.UTF8.GetString(bytes);

I've picked the UTF8 encoding here, but the encoding choice is yours. See the documentation for TEncoding for all the options.

The code in your question implicitly obtains UTF16 bytes because that's the raw string encoding in Delphi. I suspect that you used that encoding not out of any particular choice. However, if it is important to use UTF16 then change the code above to use TEncoding.Unicode.

Usually, however, UTF8 is a sound choice because it tends to be space efficient.

like image 90
David Heffernan Avatar answered Jan 30 '23 23:01

David Heffernan