是否有任何“Pos”函数来查找字节?

时间:2011-02-10 16:09:27

标签: delphi bytearray

var
  FileBuff: TBytes;
  Pattern: TBytes;
begin
  FileBuff := filetobytes(filename);
  Result := CompareMem(@Pattern[0], @FileBuff[0], Length(Pattern));
end;

是否有任何功能,如

Result := Pos(@Pattern[0], @FileBuff[0]);

2 个答案:

答案 0 :(得分:8)

我认为这样做:

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;

答案 1 :(得分:0)

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

用浏览器编写:

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;