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
.
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.
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