将TByteDynArray转换为字符串 [英] Convert TByteDynArray to string

查看:83
本文介绍了将TByteDynArray转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用网络服务,并且 在文本内容中发现无效字符 时遇到问题。我没有太多的编码经验,所以我决定将数据作为 TByteDynArray 传递。这是我在此答案中使用的代码。

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;

我成功地将 string 转换为 TByteDynArray ,但我不知道如何将其从 TByteDynArray 转换回 string

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

推荐答案

与其复制原始UTF16字节,通常不如使用 TEncoding 类即可执行此类操作。您可能会借此机会变得精通文本编码。

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.

因此,您可以使用

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

获得文本作为UTF8编码的字节。

to obtain the text as UTF8 encoded bytes.

反方向使用

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

我在这里选择了UTF8编码,但是编码选择是您自己的。请参阅 TEncoding 的所有选项。

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

您问题中的代码隐式获取UTF16字节,因为这是Delphi中的原始字符串编码。我怀疑您使用该编码不是出于任何特定选择。但是,如果重要的是使用UTF16,则将上面的代码更改为使用 TEncoding.Unicode

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.

通常,但是,UTF8是一个不错的选择,因为它倾向于节省空间。

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

这篇关于将TByteDynArray转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆