0

I want to save the value inside the Edit Box and the UTF-16 (Little Endian) value in a file. I will give a simple example to better understand my question:

Edit Box Value => 'Good';
Hex value = FFFEFF15410042004300
which is equivalent to UTF-16 (Little Endian) => ᗿABC

Now I want the value of Good and ᗿABC to be saved in a file, so that if we open the saved file with notepad, it will display the value: (ᗿABCGood) and if we open it with Hex Editor, it will display the value: (FFFEFF1541004200430047006F006F006400).

Adam Luper
  • 230
  • 9

1 Answers1

1

Your hex is simply the raw bytes of the UTF-16 (Little Endian) encoded form of the strings.

Delphi versions prior to 2009 (like Delphi 7) have very limited support for Unicode, but you can simply assign your strings to WideString (Delphi's wrapper for a UTF-16LE COM string) and then write the raw bytes of its characters to the file, prepended with a UTF-16LE BOM, eg:

uses
  Classes;

const
  BOM: WideChar = $FEFF;
var
  W: WideString;
  FS: TFileStream;
begin
  W := 'ᗿABC';
  FS := TFileStream.Create('text.txt', fmCreate);
  try
    FS.WriteBuffer(BOM, Sizeof(BOM));
    FS.WriteBuffer(PWideChar(W)^, Length(W) * Sizeof(WideChar));
  finally
    FS.Free;
  end;
end;

Since 2009, Delphi has much more support for UTF-16 strings, via UnicodeString, TEncoding.(BigEndian)Unicode etc., for example:

uses
  System.IOUtils;

begin
  TFile.WriteAllText('text.txt', 'ᗿABC', TEncoding.Unicode);
end;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770