arrays - 将字符串转换为字节数组,然后写入 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;
解决方案
我将根据描述尽可能地解释它,而不考虑提供的代码,因为它缺少关键信息。
要将字符串转换为字节数组:
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;
推荐阅读
- javascript - 似乎无法获得嵌套在 LI 标记内的 div 的父 ID
- gitlab-ci - GitLab Runner 升级后不选择作业
- git - GITLens 切换到提交使我的新提交消失了
- python - 我想在 python 中打开一个 json 文件,但出现错误。它说没有这样的文件或目录
- python - 如果同一行中的字符串具有特定值,则更改 CSV 行中的数值
- android - AndroidStudio] 布局文件中的对象未显示在代码中
- c# - 为什么检查 if(a!=null) 时出现 Null 错误
- python - 使用python和linux在for循环中重命名文件
- excel - 1 / 0 Excel 中的稀疏矩阵
- node.js - 在 Angular 项目中实现蓝牙设备连接