how do I convert a BitArray into a byte array?

22:11 [ Roadrunne] Hi, how can I get back a Byte-Array from a BitArray?
22:25 [ Flav] Roadrunne: do you want 1 bit stored per byte or 8?

BitArray bitArray = new BitArray(new bool[] {
true, true, true, false, false, false, false, false, // 7
true, false, true, false, false, false, false, false, // 5
false, false, false, true, false, false, false, false, // 8
true // 1
});

1 bit per byte would be wasteful – you’d likely want to have a bool array instead, which is easy enough to do:
bool[] boolArray = new bool[bitArray.Length];
bitArray.CopyTo(boolArray, 0);

8 bits per byte makes more sense, and you just need to allocate based on a ceiling to make sure you can fit in the number of bits you have in the BitArray (since the bitArray in the general case may not be of length 0 mod 8).
byte[] byteArray = new byte[(int)Math.Ceiling((double)bitArray.Length / 8)];
bitArray.CopyTo(byteArray, 0);

You probably noticed the BitArray declared in a “little endian” type of style – this is just reflecting how BitArray converts each set of 8 bits into a byte by default.

BitArray.CopyTo can also target Int32’s if you want that as your target. For more information, see the msdn page for BitArray.CopyTo

Advertisements