how to convert bool array in one byte and later convert back in bool array

user1688686 picture user1688686 · Jun 20, 2014 · Viewed 13.4k times · Source

I would like to pack bool array with max length 8 in one byte, send it over network and then unpack it back to bool array. Tried some solutions here already but it didn't work. I'm using Mono.

I made BitArray and then tried to convert it in byte

public static byte[] BitArrayToByteArray(BitArray bits)
    {
      byte[] ret = new byte[Math.Max(1, bits.Length / 8)];
      bits.CopyTo(ret, 0);
      return ret;
    }

but I'm getting errors telling only int and long type can be used. Tried int instead of byte but same problem. I would like to avoid BitArray and use simple conversion from bool array to byte if possible

Answer

John Willemse picture John Willemse · Jun 20, 2014

Here's how I would implement this.

To convert the bool[] to a byte:

private static byte ConvertBoolArrayToByte(bool[] source)
{
    byte result = 0;
    // This assumes the array never contains more than 8 elements!
    int index = 8 - source.Length;

    // Loop through the array
    foreach (bool b in source)
    {
        // if the element is 'true' set the bit at that position
        if (b)
            result |= (byte)(1 << (7 - index));

        index++;
    }

    return result;
}

To convert a byte to an array of bools with length 8:

private static bool[] ConvertByteToBoolArray(byte b)
{
    // prepare the return result
    bool[] result = new bool[8];

    // check each bit in the byte. if 1 set to true, if 0 set to false
    for (int i = 0; i < 8; i++)
        result[i] = (b & (1 << i)) == 0 ? false : true;

    // reverse the array
    Array.Reverse(result);

    return result;
}