Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get single byte out of BitArray (without byte[])?

Tags:

c#

.net

I was wondering, is there a way to convert a BitArray into a byte (opposed to a byte array)? I'll have 8 bits in the 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 have to change the byte array into a byte or if i can change the BitArray directly into a byte. I would prefer being able to change the BitArray directly into a byte... any ideas?

like image 716
BigBug Avatar asked Oct 23 '22 05:10

BigBug


1 Answers

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 so

        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

like image 155
Muhammad Hasan Khan Avatar answered Oct 31 '22 11:10

Muhammad Hasan Khan