Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 418
user1688686 Avatar asked Jun 20 '14 07:06

user1688686


People also ask

Why is a bool 4 bytes?

Because it's fast. A 32-bit processor typically works with 32-bit values. Working with smaller values involves longer instructions, or extra logic.

Which of the following ways is correct to convert a byte into long?

The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes).


1 Answers

Other static functions version

/// <summary>
/// Convert Byte Array To Bool Array
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static bool[] ConvertByteArrayToBoolArray(byte[] bytes)
{
    System.Collections.BitArray b = new System.Collections.BitArray(bytes);
    bool[] bitValues = new bool[b.Count];
    b.CopyTo(bitValues, 0);
    Array.Reverse(bitValues);
    return bitValues;
}

/// <summary>
/// Packs a bit array into bytes, most significant bit first
/// </summary>
/// <param name="boolArr"></param>
/// <returns></returns>
public static byte[] ConvertBoolArrayToByteArray(bool[] boolArr)
{
    byte[] byteArr = new byte[(boolArr.Length + 7) / 8];
    for (int i = 0; i < byteArr.Length; i++)
    {
        byteArr[i] = ReadByte(boolArr, 8 * i);
    }
    return byteArr;
}
like image 128
Alejandro Aranda Avatar answered Nov 15 '22 14:11

Alejandro Aranda