What is the simplest way to find a byte[] inside another byte[]? i have a feeling i could do it with linq but i dont know how.
Note: I did a search with the [c#] and didnt find anything, i am surprised.
What is the simplest way to find a byte[] inside another byte[]? i have a feeling i could do it with linq but i dont know how.
Note: I did a search with the [c#] and didnt find anything, i am surprised.
Here's a faster version of Ergwun's excellent answer:
static int SearchBytes( byte[] haystack, byte[] needle ) {
var len = needle.Length;
var limit = haystack.Length - len;
for( var i = 0; i <= limit; i++ ) {
var k = 0;
for( ; k < len; k++ ) {
if( needle[k] != haystack[i+k] ) break;
}
if( k == len ) return i;
}
return -1;
}
In a brief test with an 11MB haystack and 9 byte needle, this was about three times faster.
The optimizations are:
match() is removed.Of course for long byte arrays you'd want to use something like a Boyer-Moore search, but for many purposes a simple algorithm like this is good enough, and it has the virtue of being short and easy to understand and verify.
Here's a simple (naive?) way to do it:
static int search(byte[] haystack, byte[] needle)
{
for (int i = 0; i <= haystack.Length - needle.Length; i++)
{
if (match(haystack, needle, i))
{
return i;
}
}
return -1;
}
static bool match(byte[] haystack, byte[] needle, int start)
{
if (needle.Length + start > haystack.Length)
{
return false;
}
else
{
for (int i = 0; i < needle.Length; i++)
{
if (needle[i] != haystack[i + start])
{
return false;
}
}
return true;
}
}
Try this one with using lambda expressions:
private bool CheckPatternInArray(byte[] array, byte[] pattern)
{
int fidx = 0;
int result = Array.FindIndex(array, 0, array.Length, (byte b) =>
{
fidx = (b == pattern[fidx]) ? fidx + 1 : 0;
return (fidx == pattern.Length);
});
return (result >= pattern.Length - 1);
}
If you are after the fastest one, check solutions here.
you probably could have figured this yourself but sometimes I like to do the simple thing.
bool found = false;
int i = 0;
for(; i < byteArray.Length || found; i++)
{
if(byteArray[i] == lookingFor)
{
found = true;
}
}