Convert a BitArray to byte[] in C#

Here's an extension method that packs a C# BitArray to a byte array:

public static byte[] ToByteArray(this BitArray bits) { int numBytes = bits.Count / 8; if (bits.Count % 8 != 0) numBytes++;

byte\[\] bytes = new byte\[numBytes\];
int byteIndex = 0, bitIndex = 0;

for (int i = 0; i < bits.Count; i++) {
    if (bits\[i\])
        bytes\[byteIndex\] |= (byte)(1 << (7 - bitIndex));

    bitIndex++;
    if (bitIndex == 8) {
        bitIndex = 0;
        byteIndex++;
    }
}

return bytes;

}

Special thanks to the good people at StackOverflow! Enjoy!

This article is part of the GWB Archives. Original Author: David Brown

New on Geeks with Blogs