0

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?

Fabrizio
  • 7,603
  • 6
  • 44
  • 104
  • @DavidHeffernan: Does this matter? Let me explain the problem in greater detail.. In order to save several encrypted strings inside database, we are using our own encryption/decryption functions that work on TBytes. Due to this fact, before encrypt-decrypt, we need to convert strings in TBytes. And here comes the problem.. Two different applications should read these strings and should be able to encrypt and decrypt these (App1 has been compiled in Delphi-2007 and app2 has been compiled in XE7). – Fabrizio May 21 '15 at 15:05
  • Oh my word, now I understand. It's trivial. Just wait a moment. – David Heffernan May 21 '15 at 15:06

1 Answers1

5

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;
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • It doesn't works on Delphi-2007. As an example, the line "ShowMessage(BytesToString(StringToBytes('aaa')));" shows a dialog displaying 'a'. I think it's because SizeOf(Char) is 1 in delphi-2007. It seems to work by replacing Char with WideChar – Fabrizio May 21 '15 at 15:29
  • Sorry. I misread that comment. It is me that needs to take more care. The answer is correct now. I forgot that Char is AnsiChar on your compiler. – David Heffernan May 21 '15 at 15:35