I believe you need 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: The original response bit until the requirements are clarified:
You did not say you want to convert. For example, this will 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();
source
share