如何在Delphi

编程入门 行业动态 更新时间:2024-10-26 09:30:40
如何在Delphi-2007上将unicode字符串转换为字节数组,反之亦然(How to convert unicode strings to bytes array and vice versa on Delphi-2007)

在delphi XE7中,我们使用以下方法将一些值从字符串转换为字节,从字节转换为字符串:

MyBytes := TEncoding.Unicode.GetBytes(MyString);

MyString := TEncoding.Unicode.GetString(MyBytes);

我想编写自己的函数,在Delphi-2007上产生相同的值。 我真的不熟悉字符编码,我想我应该在delphi-2007中使用WideString类型(它是对的?)

function StringToBytes(AValue : WideString) : TBytes; begin Result := //... end; function BytesToString(AValue : TBytes) : WideString; begin Result := //... end;

有人可以帮我写这两个函数吗?

In Delphi XE7, we are converting some values from string to bytes and from bytes to string using:

MyBytes := TEncoding.Unicode.GetBytes(MyString);

and

MyString := TEncoding.Unicode.GetString(MyBytes);

I would like to write my own functions that results same values on Delphi-2007. I'm really not skilled about chars encoding, I suppose I should use WideString type in Delphi-2007 (It's right?)

function StringToBytes(AValue : WideString) : TBytes; begin Result := //... end; function BytesToString(AValue : TBytes) : WideString; begin Result := //... end;

Could someone help me in writing this two functions?

最满意答案

由于WideString是UTF-16编码的,并且您需要UTF-16编码的字节数组,因此不需要转换。 您可以像这样执行直接内存复制:

function StringToBytes(const Value : WideString): TBytes; begin SetLength(Result, Length(Value)*SizeOf(WideChar)); if Length(Result) > 0 then Move(Value[1], Result[0], Length(Result)); end; function BytesToString(const Value: TBytes): WideString; begin SetLength(Result, Length(Value) div SizeOf(WideChar)); if Length(Result) > 0 then Move(Value[0], Result[1], Length(Value)); end;

Since a WideString is UTF-16 encoded, and you want a UTF-16 encoded byte array, no conversion is needed. You can perform a direct memory copy like this:

function StringToBytes(const Value : WideString): TBytes; begin SetLength(Result, Length(Value)*SizeOf(WideChar)); if Length(Result) > 0 then Move(Value[1], Result[0], Length(Result)); end; function BytesToString(const Value: TBytes): WideString; begin SetLength(Result, Length(Value) div SizeOf(WideChar)); if Length(Result) > 0 then Move(Value[0], Result[1], Length(Value)); end;

更多推荐

本文发布于:2023-07-26 03:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1270691.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Delphi

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!