Search code examples
delphidelphi-7

How to save UTF-16 (Little Endian) and String value inside a file in Delphi 7?


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 a Hex Editor, it will display the value: FFFEFF1541004200430047006F006F006400.


Solution

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