David Brown

The Web Development Guy
posts - 5, comments - 19, trackbacks - 0

My Links

News

View David Brown's profile on LinkedIn

Twitter












Tag Cloud

Archives

Sunday, April 05, 2009

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!

posted @ Sunday, April 05, 2009 3:23 PM | Feedback (4) |

Powered by: