【问题标题】:Is there any "Pos" function to find bytes?是否有任何“Pos”函数来查找字节?
【发布时间】:2011-02-10 16:09:27
【问题描述】:
var
  FileBuff: TBytes;
  Pattern: TBytes;
begin
  FileBuff := filetobytes(filename);
  Result := CompareMem(@Pattern[0], @FileBuff[0], Length(Pattern));
end;

有没有

之类的功能
Result := Pos(@Pattern[0], @FileBuff[0]);

【问题讨论】:

标签: delphi bytearray


【解决方案1】:

我认为这样做:

function BytePos(const Pattern: TBytes; const Buffer: PByte; const BufLen: cardinal): PByte;
var
  PatternLength: cardinal;
  i: cardinal;
  j: cardinal;
  OK: boolean;
begin
  result := nil;
  PatternLength := length(Pattern);
  if PatternLength > BufLen then Exit;
  if PatternLength = 0 then Exit(Buffer);
  for i := 0 to BufLen - PatternLength do
    if PByte(Buffer + i)^ = Pattern[0] then
    begin
      OK := true;
      for j := 1 to PatternLength - 1 do
        if PByte(Buffer + i + j)^ <> Pattern[j] then
        begin
          OK := false;
          break
        end;
      if OK then
        Exit(Buffer + i);
    end;
end;

【讨论】:

  • 我会使用形式参数而不是 pbyte。意思相同,但兼容更多类型。
  • @Andreas,我认为它不会这样做:如果找不到模式,您的例程将返回一个指向第一个字节的指针......如果在第一个字节?如果没有找到模式,最好返回 nil。如果模式的第一个和第二个字节匹配,您的例程将返回第二个字节的地址并退出(无需进一步比较模式的其余部分)
  • @Andreas 没有就是太多了!
  • 不知是否有“fastcode”版本的功能。没关系,它已经像一个魅力了!
【解决方案2】:

自己写。仅查找一个字节时无法进行优化,因此您找到的任何实现基本上都会做同样的事情。

写在浏览器中:

function BytePos(Pattern:Byte; Buffer:PByte; BufferSize:Integer): Integer;
var i:Integer;
begin
  for i:=0 to BufferSize-1 do
    if Buffer[i] = Pattern then
    begin
      Result := i;
      Exit;
    end;
  Result := -1;
end;

【讨论】:

  • 我认为@user 想要多字节模式的能力
  • 是的,您只能找到一个字节模式,并且要求是多字节。
猜你喜欢
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-18
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2020-09-20
相关资源
最近更新 更多