how to convert bool array in one byte and later convert back in bool array
Without Array.Reverse version :
public static void Byte2Flags(bool[] flags, byte range)
{
if (flags == null || flags.Length < 8)
{
return;
}
for (int i = 0; i < 8; i++)
flags[i] = (range & (1 << i)) > 0;
}
public static byte Flags2Byte(bool[] flags)
{
byte range = 0;
if (flags == null || flags.Length < 8)
{
range = 0;
}
for (int i = 0; i < 8; i++)
{
if (flags[i])
{
range |= (byte)(1 << i);
}
}
return range;
}
And How to test:
bool[] flags = new bool[8];
byte b;
for(int i = 0; i < 256; i++)
{
b = (byte)i;
Byte2Flags(flags, b);
byte back = Flags2Byte(flags);
if(b != back)
{
//Not Match!
}
}
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;
// reverse the array
Array.Reverse(result);
return result;
}
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;
}