1

I was wondering what would be the best approach towards finding the index of a sub-array from within another byte array in C#. For example if I have the following as my main array.

byte[] inputArray = {0xFF,0xDD,0xA,0xF,0x1,0x2,0x78,0x05,0x00,0x01};
byte[] tobeFound = {0x78,0x05};

Now I want to find the byte array "tobeFound" inside inputArray. And I should get the index 6. This is a short example. Both arrays can be very large.

So what should I go for? LINQ, Array.IndexOf ?? I need to have good performance as well.

Thanks for any pointers and sharing some experience!

8
  • 2
    why don't you write a little console app that does performance testing on your various solutions and see which one performs the best Commented Nov 3, 2011 at 6:18
  • you could do pretty much the same as this stackoverflow.com/questions/4190533/… Commented Nov 3, 2011 at 6:21
  • @Mark, i use bytes, not strings Commented Nov 3, 2011 at 6:22
  • @Jason, if someone has done it, may be can guide me with some info about speed before I write the code. That is why I requested to share some experience. Commented Nov 3, 2011 at 6:23
  • 1
    @Wajih: Dude..a string is an array of chars. Replace string with byte[] in the example I gave you, and it'll work. I thought you'd piece that together. Commented Nov 3, 2011 at 6:32

1 Answer 1

7

You can use the well-tested Boyer-Moore string search algorithm, since you are essentially searching a string (the bytes can be considered characters).

Here is what appears to be a decent implementation of Boyer-Moore in C# for strings (along with turbo Boyer-Moore and another I'd never heard of). Converting these to use Byte[] should be trivial.

Sign up to request clarification or add additional context in comments.

3 Comments

well I am not searching strings actually,I am limited to bytes.
The essence is the same: a string is just a sequence of bytes. The algorithm will work equally well for a byte array.
@codekaizen: That's a cool algorithm! Never would have thought of that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.