Thursday, February 24, 2011

.NET: C# find pattern in byte array

Byte Arrays are not as easily handled as strings when it comes to finding what they contain, especially if we are searching for a pattern of matching bytes.
It seems like everyone is rolling their own on this one. Most examples I have seen look at converting bytes to strings and then using IndexOf operators.
However, if you use bytes that cannot be converted to a string easily or do not want to use string comparison here is my version of a working function that does the trick.


private static int ByteSearch(byte[] searchIn, byte[] searchBytes, int start = 0)
{
int found = -1;
bool matched = false;
//only look at this if we have a populated search array and search bytes with a sensible start
if (searchIn.Length > 0 && searchBytes.Length > 0 && start <= (searchIn.Length - searchBytes.Length) && searchIn.Length >= searchBytes.Length)
{
//iterate through the array to be searched
for (int i = start; i <= searchIn.Length - searchBytes.Length; i++)
{
//if the start bytes match we will start comparing all other bytes
if (searchIn[i] == searchBytes[0])
{
if (searchIn.Length > 1)
{
//multiple bytes to be searched we have to compare byte by byte
matched = true;
for (int y = 1; y <= searchBytes.Length - 1; y++)
{
if (searchIn[i + y] != searchBytes[y])
{
matched = false;
break;
}
}
//everything matched up
if (matched)
{
found = i;
break;
}

}
else
{
//search byte is only one bit nothing else to do
found = i;
break; //stop the loop
}

}
}

}
return found;
}





Cheers,
B.

4 comments:

Techie said...

Hi,
I am trying to use the code for a byte array which has a both readable text and binary data but the code returns 0 as the index. I am looking for a pattern which is around 40 in length. I have a multipart/mixed http response stream which has a boundary defined. I want to have the indexes of the boundary.

Thanks
Sri

bman said...

if zero if returned as index it would normally mean that a match was found starting with the first byte.
Is that incorrect?
Can you send a post a sample?

YPermitin said...

Thanks! This is work for me!

moshrabbi121 said...

I am usually to running a blog and i really respect your content. The article has actually peaks my interest. I'm going to bookmark your web site and maintain checking for brand new information. online casino slots