Search code examples
stringdelphiunicodeencodingdelphi-2007

How to convert unicode strings to bytes array and vice versa on Delphi-2007


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?


Solution

  • 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;