【问题标题】:Delphi How to replace data in Hex fileDelphi如何替换Hex文件中的数据
【发布时间】:2016-04-09 01:00:00
【问题描述】:

要将文件内容加载为十六进制,我在 Delphi 7 中使用此代码:

procedure ReadFileAsHex(const AFileName: string; ADestination: TStrings);
var fs: TFileStream;
    buff: Byte;
    linecount: Byte;
    line: string;
begin
  linecount := 0;
  line := '';
  fs := TFileStream.Create(AFileName, fmOpenRead);
  try
    while fs.Position < fs.Size do begin
      fs.Read(buff, 1);
      line := line + IntToHex(buff, 2) + ' ';
      Inc(linecount);
      if linecount = 16 then begin
        ADestination.Add(line);
        line := '';
        linecount := 0;
      end;
    end;
    if Length(line) <> 0 then
      ADestination.Add(line);  
  finally
    fs.Free;
  end;
end;

这向我显示了像这样以十六进制加载的文件:

34 01 00 00 13 00 00 00 13 00 00 00 04 00 00 00
01 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00
34 01 00 00 13 00 00 00 13 00 00 00 04 00 00 00
01 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00

我想替换实际文件中的一些数据

例如 我想将数据从 Offset(00000060) 替换为 Offset(00000070) 例如用 00 all 有没有可能,或者我需要一些特殊的组件?

谢谢

【问题讨论】:

  • 不清楚你在问什么。您要替换ADestination(字符串表示)还是实际文件本身(fs)中的内容?
  • 嗨,这只是我如何加载文件的示例,我想替换实际文件中的内容

标签: delphi hex delphi-7 edit


【解决方案1】:

没有“写十六进制”之类的东西。十六进制只是一种表示数字并更容易执行一些数学运算的方法。十六进制值$00 与十进制值0 完全相同,如果以数字形式写入文件,它们是完全相同的。如果你写$FF和十进制255,也是如此;它们最终在文件中作为相同的值,以相同的方式写入。

换句话说,将以下任一变量写入文件将导致完全相同的文件内容:

const
  DecimalZero = 0;
  HexZero = $0;

这些也可以这样说:

const
  DecimalTwoFiftyFive = 255;
  HexTwoFiftyFive = $FF;

您可以告诉您实际上是在读取数字(非文本)值,因为您发布的代码必须在值上使用 IntToHex 才能将其转换为十六进制字符串,然后才能将其添加到line 变量,声明为 string

您正在讨论将二进制(非文本)写入文件,这只是意味着将实际数值写入文件,而不是这些数字的文本表示。

您只需将TFileStream 定位到您想要开始写入的位置,然后将您想要的字节数写入文件。您必须以写入模式打开流,而不是像您的代码使用 fmOpenRead 那样以只读方式打开流。

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);

  fs := TFileStream.Create(AFileName, fmOpenWrite);
  try
    fs.Position := 60;                 // Set to starting point of write
    fs.Write(Buff[0], Length(Buff));   // Write bytes to file
  finally
    fs.Free;
  end;
end;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-14
    • 2023-01-30
    • 1970-01-01
    • 2020-02-22
    • 2020-06-15
    • 1970-01-01
    • 2019-06-04
    • 2011-06-08
    相关资源
    最近更新 更多