How to convert strings to array of byte and back

ぃ、小莉子 提交于 2019-11-30 12:17:50

Delphi strings are encoded internally as UTF-16. There was a big clue in the fact that SizeOf(Char) is 2.

The reason that all your characters had ordinal in the ASCII range is that UTF-16 extends ASCII in the sense that characters 0 to 127, in the ASCII range, have the same ordinal value in UTF-16. And all your characters are ASCII characters.

That said, you do not need to worry about the internal storage. You simply convert between string and byte array using the TEncoding class. For instance, to convert to UTF-8 you write:

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

And in the opposite direction:

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

The class supports many other encodings, as described in the documentation. It's not clear from the question which encoding you are need to use. Hopefully you can work the rest out from here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!