How do I search for a byte array for "StringA"?

Using FreePascal (or Delphi if there are no FP examples), given a 2048 byte buffer which is a "byte array", how can I search for a buffer for "StringA"?

var
Buffer : array[1..2048] of byte;
...
  repeat
      i := 0;
      BlockRead(SrcFile, Buffer, SizeOf(Buffer), NumRead);      
      // Now I want to search the buffer for "StringA"? 
...

      

Thankyou

+3


source to share


2 answers


I think this will work in fpc without additional Unicode / AnsiString conversion:



function Find(const buf : array of byte; const s : AnsiString) : integer;
//returns the 0-based index of the start of the first occurrence of S
//or -1 if there is no occurrence
var
  AnsiStr : AnsiString;
begin
  SetString(AnsiStr, PAnsiChar(@buf[0]), Length(buf));
  Result := Pos(s,AnsiStr) - 1;  // fpc has AnsiString overload for Pos()
end;

      

+6


source


Here's a naive approach where we just loop through the byte buffer by byte looking for the desired string.

function Find(const Buffer: array of Byte; const S: AnsiString): Integer;
//returns the 0-based index of the start of the first occurrence of S
//or -1 if there is no occurrence
var
  N: Integer;
begin
  N := Length(S);
  if N>0 then
    for Result := low(Buffer) to high(Buffer)-(N-1) do
      if CompareMem(@Buffer[Result], Pointer(S), N) then
        exit;
  Result := -1;
end;

      



I'm not using FPC, but I expect this to work unchanged, and if not, then I'm sure you can convert it.

+4


source







All Articles