Checking for a bit pattern
I have an array of 30 bytes and need to parse through it checking for a 7 bit pattern of 0100111 when found move foward 233 bit into the next frame and check for the alternate pattern of 1011000 I'm having problems changing from a byte array to a bitarray can anyone point me in the right direction??
Mike GoldPosted Aug 30, 2007, 7:32 PM
A bit array will take an array of bytes in the constructor, so you can just pass in the byte array. Alan's solution may be a little easier though. It doesn't seem that Microsoft provides a method to take a piece of the BitArray. CopyTo is the closest thing, at this copies the entire array at a specific index.
BitArray mainarray = new BitArray(myBytes);
Theoretically their may be a way to do the comparison by sliding a BitArray with your pattern along the big bitarray record and the Xor method of the BitArray , also masking the other bits in the main array with 0000s (using the And method of the BitArray). Then use CopyTo to copy the entire contents to a boolean array, and essentially search for a single true boolean value.
gordonPosted Aug 30, 2007, 10:44 AM
AlanPosted Aug 30, 2007, 9:11 AM
If you don't mind using strings for this, then the following approach should work. I've just used a 5 byte array for illustration and, as expected, the pattern is found at bit 17 (zero based):
using System;
using System.Text;
class Program
{
static void Main()
{
byte[] ba = new byte[5]{1, 2, 39, 4, 5};
string pattern = "0100111"; // decimal 39
StringBuilder sb = new StringBuilder(8 * ba.Length);
int temp = 0;
foreach (byte b in ba)
{
temp = int.Parse(Convert.ToString(b, 2));
sb.Append(temp.ToString("00000000"));
}
string bitArray = sb.ToString();
Console.Clear();
Console.WriteLine("Bitarray is {0}", bitArray);
Console.WriteLine("Pattern is {0}\n", pattern);
int index = bitArray.IndexOf(pattern);
if (index == -1)
Console.WriteLine("Pattern wasn't found");
else
Console.WriteLine("Pattern first occurred at bit {0}", index);
Console.ReadKey();
}
}