Re: Searching in byte buffer



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
.



Relevant Pages

  • Re: Data type byte
    ... attempt to change the input buffer to a string (although not by changing the ... With multi dimensional array that can hold ... Also the receiving ... dimensional Byte Array is just one long string of memory. ...
    (microsoft.public.vb.general.discussion)
  • Re: String parsing in VB.net
    ... refactor your code so that myDataBuffer is an array of Byte, ... than a string. ... receives a data buffer. ... encoding - it is only defined for 0-127. ...
    (microsoft.public.dotnet.languages.vb)
  • Re: from array of ints to string and vice versa
    ... I want to convert this string to an array, ... other to generate it, separating them with ", ". ... takes a buffer and returns a size, which you first call with a NULL pointer ...
    (comp.programming)
  • Re: pls help: very odd behaviour when concatenating strings
    ... More then likely you are having a problem because your byte array is ... array to a string. ... // Put some stuff in the buffer. ... > concatenate them some values are missing (I canīt see them in the debugger). ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Help With Arrays
    ... > The string to be copied to the buffer is of varying size, ... making the size of the string the same size as the array. ... The way round this is to use malloc(). ...
    (comp.lang.c)