coolirc
coolirc

Reputation: 43

convert string to array of byte then write to bin file

Hello i want to convert string to array of bytes then save the bytes at position in hex format to bin file

When I open the binary file using a hex editor and I search for the selected position there is a date example 21-01-2020 so i want to replace it by today's date. Via a TEdit.Text or via a TDateTimePicker or a function that returns to current system date and write directly to the selected offset the desired value.

I'm using this code already found in StackOverflow but it only writes one character I want to write for example date from edit1.text to bin file at position x

here's the code :

procedure TForm7.Button1Click(Sender: TObject);
   var
  fs: TFileStream;
  Buff: array of byte;
   begin

    // Set length of buffer and initialize buffer to zeros
       SetLength(Buff, 10);
      FillChar(Buff[0], Length(Buff), #0); // this will write 0 to 10 bytes 
    fs := TFileStream.Create('F:\test\file.bin', fmOpenWrite);
   try
   fs.Position := $15c20;                 // Set to starting point of write
   fs.Write(Buff[0], Length(Buff));   // Write bytes to file
   finally
  fs.Free;
  end;
end;

Upvotes: 1

Views: 375

Answers (2)

fpiette
fpiette

Reputation: 12322

There is no conversion required! Just write the string, according to your comment, you must write ansi string (one byte per character). For a date, a simple cast to AnsiString is enough. The compiler emit a warning because such as cast would not work as expected for accented character or Chineese, or so. I used a compiler directive to turn that warning off.

I have no more Delphi 10.1, but the code below should work with that old compiler.

procedure TForm1.Button1Click(Sender: TObject);
var
    Buffer     : AnsiString;
    FileName   : String;
    FileStream : TFileStream;
begin
    {$WARN IMPLICIT_STRING_CAST_LOSS OFF}
    Buffer     := String(FormatDateTime('MM-DD-YYYY', Now));
    FileName   := 'E:\Temp\file.bin';
    if not FileExists(FileName) then begin
        ShowMessage('File not found: "' + FileName + '"');
        Exit;
    end;

    FileStream := TFileStream.Create(FileName, fmOpenReadWrite);
    try
        FileStream.Seek($15c20, soBeginning);
        FileStream.Write(Buffer[1], Length(Buffer));
    finally
        FileStream.Free;
    end;
end;

Upvotes: 1

Juan Medina
Juan Medina

Reputation: 559

I will try to explain it as best as I can as per the description and not taking the code provided into consideration, because it's missing key information.

To convert a string to a byte array:

byteArray := TEncoding.UTF8.GetBytes('some string');

To insert the byte array into a file having an offset:

fileStream := System.IO.FileStream.Create('F:\test\file.bin', FileMode.OpenOrCreate);
fileStream.Seek($15c20, SeekOrigin.Begin);
fileStream.Write(byteArray,0,Length(byteArray));
fileStream.Close;

Upvotes: 1

Related Questions