首页 > 解决方案 > 将字符串转换为字节数组,然后写入 bin 文件

问题描述

您好,我想将字符串转换为字节数组,然后将位置的字节以十六进制格式保存到 bin 文件中

当我使用十六进制编辑器打开二进制文件并搜索所选位置时,有一个日期示例 21-01-2020 所以我想用今天的日期替换它。通过 TEdit.Text 或通过 TDateTimePicker 或返回当前系统日期并直接将所需值写入所选偏移量的函数。

我正在使用已经在 StackOverflow 中找到的这段代码,但它只写了一个我想写的字符,例如从 edit1.text 到 bin 文件位置 x 的日期

这是代码:

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;

标签: arraysstringdelphibyte

解决方案


我将根据描述尽可能地解释它,而不考虑提供的代码,因为它缺少关键信息。

要将字符串转换为字节数组:

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

要将字节数组插入到具有偏移量的文件中:

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

推荐阅读