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
Because it's fast. A 32-bit processor typically works with 32-bit values. Working with smaller values involves longer instructions, or extra logic.
The BigInteger class has a longValue() method to convert a byte array to a long value: long value = new BigInteger(bytes).
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With