Search code examples
c#lsb

LSB from array of bytes C#


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;
        }

Solution

  • 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);
    }