Is there any “Pos” function to find bytes?

旧街凉风 提交于 2019-12-09 18:30:08

问题


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

Is there any function such as

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

回答1:


I think this does it:

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;



回答2:


Write your own. No optimization can be done when looking for just one byte, so any implementation you'll find would basically do the same thing.

Written in browser:

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;


来源:https://stackoverflow.com/questions/4959566/is-there-any-pos-function-to-find-bytes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!