在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;更多推荐
发布评论