Finding a pattern of bytes within an Array of bytes.

Mr_Fulano
Mr_Fulano used Ask the Experts™
on
Hi, I'm using MS VS2010, C#.NET. I have an Array of bytes wherein I need to identify a pattern of multiple bytes. Much like the IndexOf() method does, but with an array of bytes.

Therefore, if my array contained "0A0A0A0A" (which is four tens in a row), I would like to know the index of where that pattern begins.

I came up with a way to find a NULL value, but it doesn't work for patterns of multiple bytes. Can someone provide some help to get me back on track?

Obviously I can convert the bytes to string and then look for the string equivalent, but there has to be a way to do it without so many conversions, which can cause "misreads".

Thanks,
Fulano


// hexAddress - the starting address of the string
// bytes2ReadAsString - the amount of bytes to read past the starting point.

private string findNull(string hexAddress, string bytes2ReadAsString)
        {
            int counter = 0;
            string i = "";
            
            br.BaseStream.Position = (Int32.Parse(hexAddress, System.Globalization.NumberStyles.HexNumber));
            foreach (byte mybyte in br.ReadBytes(Convert.ToInt32(bytes2ReadAsString)))
            {
                
                if (mybyte.Equals(0x0))
                {
                    break;
                }
                counter++;
            }
                       
            i = counter.ToString("X");

            // This returns the index of where the NULL begins.
            return i;
            
        }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Hi Mr_Fulano,

Does this help?

.NET: C# find pattern in byte array
http://boncode.blogspot.co.uk/2011/02/net-c-find-pattern-in-byte-array.html

Author

Commented:
Hi Rimvis, I think it will help, but I'm still trying to figure out what arguments to pass it. It looks like I have to pass it two different Arrays of bytes. However, I have one Array and one string of bytes. For example:

My array is:  myBytes

My Pattern is: 0A0A0A0A

So, I'd like to pass it the arguments like this:

ByteSearch( myBytes, "0A0A0A0A", 0);

However, that won't work. I need make the pattern into an Array -- I think....

Still working on it.

Fulano

Commented:
Hi,

to convert hex string into byte array, you can use this:
http://pcheruku.wordpress.com/2008/10/21/sample-c-code-to-convert-hexadecimal-string-to-bytes/

Author

Commented:
Thank Rimvis...very good samples. These worked well together.

Thanks again!

Author

Commented:
Both sets of code are excellent!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial