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

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!

Print | posted on Sunday, April 05, 2009 3:23 PM |

Feedback

Gravatar

# re: Convert a BitArray to byte[] in C#

You should be VERY careful using an extension method like that in production code.

Just on a cursory glance I can see that it could throw a dividebyzero exception and an indexofbounds exception. You would at the least want to ensure that any consumer code was aware of this potential.
5/15/2009 2:16 PM | Steve Hoff
Gravatar

# re: Convert a BitArray to byte[] in C#

A common approach to do the conversion is:

byte[] bytes = new byte[bits.Length];
array.CopyTo(bits, 0);
8/8/2009 7:35 PM | mcm
Gravatar

# re: Convert a BitArray to byte[] in C#

Sorry should be:

byte[] bytes = new byte[bits.Length];
bits.CopyTo(bytes, 0);
8/8/2009 7:37 PM | mcm
Gravatar

# re: Convert a BitArray to byte[] in C#

Actually, that didn't work in my case. It came up in the discussion on StackOverflow. The CopyTo method produced the wrong result for some reason. To use it, you have to first reverse the original array before passing it to the constructor of BitArray. After your call to CopyTo, you then have to reverse the byte array. It's a bit of a hassle, but this extension method does it correctly from the start.
8/8/2009 9:46 PM | David Brown
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 

Powered by: