Search code examples
delphidelphi-7

How do I convert an array of bytes to string with Delphi?


I am developing a project with Delphi and I want to convert the byte array to string type. How can I do?

Example C# codes:

private void ListenerOnDataTransmit(DataTransmitEventArgs e)
{
    transmittedMsg = BitConverter.ToString(e.TransmittedBytes, 0, e.TransmittedBytes.Length);
    try { Invoke(new EventHandler(UpdateTransmittedMessagesListView)); }
    catch { }
}

Solution

  • The BitConverter.ToString() method "Converts the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string representation." You can do the same thing manually in Delphi 7 by using the SysUtils.IntToHex() function in a loop, eg:

    uses
      ..., SysUtils;
    
    var
      bytes: array of byte;
      s: string;
      i: Integer;
    begin
      bytes := ...;
      s := '';
      if bytes <> nil then
      begin
        s := IntToHex(bytes[0], 2);
        for i := 1 to High(bytes) do
          s := s + '-' + IntToHex(bytes[i], 2);
      end;
    end;