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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With