将TBytes(UTF-16)转换为字符串的最佳方式是什么? [英] What is the best way to convert TBytes (UTF-16) to a string?

查看:275
本文介绍了将TBytes(UTF-16)转换为字符串的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Delphi 2009中,将TBytes的字节数组转换为unicode字符串的最佳方式是什么?在我特定的情况下,TBytes数组已经有UTF-16编码数据(每个字符为2个字节)。



由于TBytes不存储一个空终止符,所以以下只有当数组恰好在与它相邻的内存中有#0时才会工作。

  MyString:= string(myBytes); 

如果没有,字符串结果将在最后有随机数据(它也可能导致读取违反取决于在内存中遇到#0的时间)。



如果我使用ToBytes函数,它返回't'#0'e'#0 '#0't'#0,这不是我想要的。

解决方案

我最后使用

  TEncoding.Unicode.GetString(MyByteArray); 


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.

解决方案

I ended up using

TEncoding.Unicode.GetString( MyByteArray );

这篇关于将TBytes(UTF-16)转换为字符串的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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