tags:

views:

4472

answers:

3

I have a BitArray with the length of 8, and I need a function to convert it to a byte. How to do it?

Specifically, I need a correct function of ConvertToByte

    BitArray bit=new BitArray(new bool[]
                                  {
                                      false,false,false,false,
                                      false,false,false,true
});
    //How to write ConvertToByte
    byte myByte=ConvertToByte(bit);
    var recoveredBit = new BitArray(new[] { myByte });
    Assert.AreEqual(bit, recoveredBit);
+5  A: 

This should work:

byte ConvertToByte(BitArray bits)
{
    if (bits.Count != 8)
    {
        throw new ArgumentException("bits");
    }
    byte[] bytes = new byte[1];
    bits.CopyTo(bytes, 0);
    return bytes[0];
}
Jon Skeet
Mind: this computes the bits in reverse order, e.g. the BitArray from the example will convert into 128, not 1!
tehvan
Why does this happen in a reverse order?
kornelijepetak
@kornelijepetak: That's just the way that BitArray works, in terms of the way it chooses to copy values.
Jon Skeet
@kornelijepetak: It is important that it copies in reverse order. If you use BitConverter on other types they are stored in little-endian format.
Shiftbit
+2  A: 

This should do the trick. However the previous answer is quite likely the better option.

    public byte ConvertToByte(BitArray bits)
    {
        if (bits.Count > 8)
            throw new ArgumentException("ConvertToByte can only work with a BitArray containing a maximum of 8 values");

        byte result = 0;

        for (byte i = 0; i < bits.Count; i++)
        {
            if (bits[i])
                result |= (byte)(1 << i);
        }

        return result;
    }

In the example you posted the resulting byte will be 0x80. In other words the first value in the BitArray coresponds to the first bit in the returned byte.

Caleb Vear
+2  A: 

A poor man's solution:

protected byte ConvertToByte(BitArray bits)
{
    if (bits.Count != 8)
    {
        throw new ArgumentException("illegal number of bits");
    }

    byte b = 0;
    if (bits.Get(7)) b++;
    if (bits.Get(6)) b += 2;
    if (bits.Get(5)) b += 4;
    if (bits.Get(4)) b += 8;
    if (bits.Get(3)) b += 16;
    if (bits.Get(2)) b += 32;
    if (bits.Get(1)) b += 64;
    if (bits.Get(0)) b += 128;
    return b;
}
tehvan