LSB from array of bytes C#

1.9k Views Asked by At

I need to select from an array of bytes an array of least significant bits into BitArray. I have code for searching lsb. But I don't know how add this array to BitArray

private static bool GetBit(byte b)
        {
            return (b & 1) != 0;
        }
2

There are 2 best solutions below

1
On BEST ANSWER

So first I would convert it to a bool array and then create the BitArray from this bool array :

static void Main(String[] args)
{
    byte[] byteArray = new byte[] { 1, 2, 3, 4, 5, 6 };
    BitArray bitArray = transform(byteArray);
}

private static bool GetBit(byte b)
{
    return (b & 1) != 0;
}

private static BitArray transform(byte[] byteArray)
{
    bool[] boolArray = new bool[byteArray.Length];
    for(int i = 0; i < byteArray.Length; i++)
    {
        boolArray[i] = GetBit(byteArray[i]);
    }
    return new BitArray(boolArray);
}

Edit:
Here is the solution with an array of arrays :

static void Main(String[] args)
{
    byte[][] byteArrays = new byte[2][];
    byteArrays[0] = new byte[] { 1, 2, 3, 4, 5, 6 };
    byteArrays[1] = new byte[] { 1, 2, 3, 4, 5, 6 };
    BitArray[] bitArrays = new BitArray[byteArrays.Length];
    for(int i = 0; i < byteArrays.Length; i++)
    {
        byte[] byteArray = byteArrays[i];
        bitArrays[i] = transform(byteArray);
    }
}

private static bool GetBit(byte b)
{
    return (b & 1) != 0;
}

private static BitArray transform(byte[] byteArray)
{
    bool[] boolArray = new bool[byteArray.Length];
    for(int i = 0; i < byteArray.Length; i++)
    {
        boolArray[i] = GetBit(byteArray[i]);
    }
    return new BitArray(boolArray);
}
1
On
    static void Main(string[] args)
    {
        byte[] bytes = new byte[] { 5, 7, 8, 1, 3, 5, 6, 1, 0 };
        byte[] b = bytes.Where(q => GetBit(q) == true).ToArray();
        BitArray bitArray = new BitArray(b);            
        Console.Read();
    }

    private static bool GetBit(byte b)
    {
        return (b & 1) != 0;
    }