I have bool array:
bool[] b6=new bool[] {true, true, true, true, true, false, true, true,
true, false, true, false, true, true, false, false };
How can I convert this into an array of bytes such that
I believe you want something like this:
static byte[] ToByteArray(bool[] input)
{
if (input.Length % 8 != 0)
{
throw new ArgumentException("input");
}
byte[] ret = new byte[input.Length / 8];
for (int i = 0; i < input.Length; i += 8)
{
int value = 0;
for (int j = 0; j < 8; j++)
{
if (input[i + j])
{
value += 1 << (7 - j);
}
}
ret[i / 8] = (byte) value;
}
return ret;
}
EDIT: Original bit of answer before the requirements were clarified:
You haven't said what you want the conversion to do. For example, this would work:
byte[] converted = Array.ConvertAll(b6, value => value ? (byte) 1 : (byte) 0);
Or similarly (but slightly less efficiently) using LINQ:
byte[] converted = b6.Select(value => value ? (byte) 1 : (byte) 0).ToArray();
If you want to convert each group of eight booleans into a byte, you can use the BitArray
class:
byte[] data = new byte[2];
new BitArray(b6).CopyTo(data, 0);
The array data
now contains the two values 0xDF and 0x35.
If you want the result 0xFB and 0xAC, you would have to reverse the booleans in the array first:
Array.Reverse(b6, 0, 8);
Array.Reverse(b6, 8, 8);
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