How to get one byte from BitArray (without byte [])?

I was wondering if there is a way to convert BitArray to bytes (against an array of bytes)? I will have 8 bits in BitArray ..

 BitArray b = new BitArray(8);


//in this section of my code i manipulate some of the bits in the byte which my method was given. 

 byte[] bytes = new byte[1];
 b.CopyTo(bytes, 0);

This is what I have so far ... It doesn’t matter if I need to change the byte array into bytes, or I can change the BitArray directly into bytes. I would prefer to modify BitArray directly in the byte ... any ideas?

+5
source share
1 answer

You can write an extension method

    static Byte GetByte(this BitArray array)
    {
        Byte byt = 0;
        for (int i = 7; i >= 0; i--)
            byt = (byte)((byt << 1) | (array[i] ? 1 : 0));
        return byt;
    }

You can use it like that

        var array = new BitArray(8);
        array[0] = true;
        array[1] = false;
        array[2] = false;
        array[3] = true;

        Console.WriteLine(array.GetByte()); <---- prints 9

9 decimal = 1001 in binary format

+3
source

All Articles