2

Simple question: considering that a bool (true, false) is the same as a bit (1, 0), what is the correct way to convert eight bools into a byte in C#?

Examples:

true, true, true, true, true, true, true, true == 11111111 == 255

true, false, false, false, false, false, false, false == 10000000 == 128

false, false, false, false, false, false, false, false == 00000000 == 0

The above is the first part. I want to create an extension method, like that:

    public static byte[] ToByteArray(this bool[] bitArray)
    {
          // stuff here
          return byteArray;    
    }

The result must be a byteArray that contains eight times less elements than the bool array.

Guilherme
  • 5,143
  • 5
  • 39
  • 60

2 Answers2

13

You probabbly searching for BitArray Constructor (Boolean[])

For rapresenting bits you have special structure BitArray in C#. So your code would look like this:

var booleans = new bool[]{true, false, false, false};
var bitArray = new BitArray(booleans); 
Tigran
  • 61,654
  • 8
  • 86
  • 123
1

Robust solution (just in case).

Split them into groups of 8 somehow (depending on the order and how you want to adjust them - to LSB or RSB), then form an array by calling this method in the cycle:

byte GetByte(bool[] bits)
{
    byte result = 0;
    for(int i = 0; i < bits.Length; i++)
        if(byte[i])
            result |= 1 << i;
    return result;
}
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
Sinatr
  • 20,892
  • 15
  • 90
  • 319
  • @LS_dev, yeah thanks. I mentioned, what `bytes` for method should be *prepared* first ^^, but you can add bound check and throw `ArgumentOutOfRangeException` or whatever if you want to, it was just an example of how easy to convert anything into bits. – Sinatr Sep 11 '13 at 06:51