I am writing a function to search in the binary array(bitmap file) a pattern of bits. The size of the pattern is from 5 to 8 bit long. I have implemented this function as testing for each bit in the array and in the pattern. However, it is not as efficient as it should be.
First of all I want to implement this code in C.
Point* FindPattern(imgInfo* pImg, int pSize, int* ptrn, Point* pDst, int* fCnt)
{
int i, j, k, l;
int mask;
int rx = pSize >> 16;
int ry = pSize & 0xFFFF;
*fCnt = 0;
for (i=0; i < pImg->height - ry; ++i)
for (j=0; j < pImg->width - rx; ++j)
{
// for a rectangle with upper lefr corner in (i,j)
// check if there is pattern in image
for (k=0; k < ry; ++k)
{
mask = 1 << (rx - 1);
for (l=0; l < rx; ++l, mask >>= 1)
if (GetPixel(pImg, j+l, i+k) != ((ptrn[k] & mask) != 0))
break;
if (l < rx) // pattern not found
break;
}
if (k >= ry) //pattern found
{
pDst[*fCnt].x = j;
pDst[*fCnt].y = i;
++(*fCnt);
}
}
For example I have such binary string: 1111 1111 1010 0000 0111 1111 1111 1111
and I am looking for pattern: 0100 0000
so what is the most efficient way to detect such a pattern in a string? By shifting the bits of the pattern and the string and than perfrom XOR on them?