Re: Searching in byte buffer



Thanks, Sherlock. I will try this out. Incidently, I also found a routine in TurboPowers SysUtil package that also I am looking at.

StBase.Search and StBase.SearchUC which search a buffer for specified pattern of bytes.

Jatin
==============


Nicholas Sherlock wrote:
Jatin wrote:

I want to search a byte buffer for certain pattern of bytes. It is similar to searching for a substring within a string, however I want to perform search on a byte buffer (array) for series of bytes. Also, it needs to be a fast search, as search is performed on bytes retrieved from soundcard buffer.

Is there a Delphi function that I can use? I found StrUtils.SearchBuf(), but it operates on strings.


Nasty and barely tested, and there are faster solutions, but this one is fairly universal:

{$R-}
function ByteSearch(buffer: pbytearray; bufsize: integer; searchpattern: pbytearray; patternsize: integer): integer;
var i, isub: integer;
match: boolean;
begin
result := -1;
for i := 0 to bufsize - 1 do
if buffer[i] = searchpattern[0] then begin
match := true;
for isub := 1 to patternsize - 1 do
if buffer[i + isub] <> searchpattern[isub] then begin
match := false;
break;
end;
if match then begin
result := i;
exit;
end;
end;
end;
{$R+}



const data: array[0..19] of byte = (1, 2, 5, 1, 32, 87, 2, 3, 34, 1, 23, 8, 2, 55, 19, 182, 72, 201, 241, 29);
search: array[0..1] of byte = (2, 3);
begin
showmessage(inttostr(bytesearch(@data[0], length(data), @search[0], length(search))));
end;


Cheers,
Nicholas Sherlock
.