Pelles C forum
C language => Beginner questions => Topic started by: bitcoin on June 11, 2021, 10:57:37 PM
-
Hello,
Are any public algorithm to find binary pattern (string)? As example - I wan't to find string "\x55\x8B\xEC\x90\x90" in PE file, strstr don't works.
-
Boyer-Moore
https://www.geeksforgeeks.org/boyer-moore-algorithm-for-pattern-searching/ (https://www.geeksforgeeks.org/boyer-moore-algorithm-for-pattern-searching/)
https://en.wikipedia.org/wiki/Boyer–Moore_string-search_algorithm (https://en.wikipedia.org/wiki/Boyer–Moore_string-search_algorithm)
-
Hi bitcoin,
Grincheux is right, the Boyer Moore Algorithms can do the job. Here are some procedures provided by the Masm32 package :
Boyer Moore Algorithms
BMBinSearch proc startpos:DWORD,
lpSource:DWORD,srcLngth:DWORD,
lpSubStr:DWORD,subLngth:DWORD
BMHBinsearch proc startpos:DWORD,
lpSource:DWORD,srcLngth:DWORD,
lpSubStr:DWORD,subLngth:DWORD
SBMBinSearch proc startpos:DWORD,
lpSource:DWORD,srcLngth:DWORD,
lpSubStr:DWORD,subLngth:DWORD
Description
The three algorithms are variations of a Boyer Moore binary search design that is well suited for very high speed searching of binary or text data for a subpattern.
Parameters
1. startpos Zero based start address to nominate where to start searching.
2. lpSource The address of the data to be searched.
3. srcLngth The length of the search data.
4. lpSubStr The address of the pattern to search for.
5. subLngth The length of the pattern to search for.
-
Hi bitcoin,
Here is a quick example for you :
#include <stdio.h>
extern int __stdcall BMBinSearch(int,char *,int,char *,int);
int main(void)
{
char s[]={0x1,0x2,0x4,0x10,0x3,0x0,0x5,0x6,0x12};
char t[]={0x3,0x0,0x5};
int u;
u=BMBinSearch(2,s,9,t,3);
printf("Zero based offset of the pattern 0x3,0x0,0x5 = %d",u);
}
-
If you just want a "KISS" C solution, something like this should work too...
void *memstr(const void *memptr, size_t memlen, const char *strptr)
{
if (*strptr == '\0')
return (void *)memptr;
size_t patlen = strlen(strptr), len;
const unsigned char *pat = (const unsigned char *)strptr;
const unsigned char *ptr = memptr;
const unsigned char *end = ptr + memlen - patlen + 1;
for (;;)
{
for ( ; ptr < end && *ptr != *pat; ++ptr)
;
if (ptr == end)
break;
for (len = 1; len < patlen && ptr[len] == pat[len]; ++len)
;
if (len == patlen)
return (void *)ptr;
++ptr;
}
return NULL;
}
-
Thank you! All works!