How to convert bool [] to byte []

I have a 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 to an array of bytes so that

  • byte [0] = 0xFB
  • byte [1] = AC
  • etc.
+5
source share
5 answers

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();
+10
source

If you want to convert each group from eight booleans to bytes, you can use a class BitArray:

byte[] data = new byte[2];
new BitArray(b6).CopyTo(data, 0);

Now the array datacontains two values: 0xDF and 0x35.

Edit:

If you want to get the result 0xFB and 0xAC, you will have to cancel the booleans in the array first:

Array.Reverse(b6, 0, 8);
Array.Reverse(b6, 8, 8);
+6
bytes = (from bit in b6 select bit ? (byte)1 : (byte)0).ToArray()
+2

Linq:

var byteArray = 
b6
.Select(b => (byte)(b ? 1 : 0))
.ToArray();
+2
byte[] byteArray = Array.ConvertAll(b6, b => b ? (byte)1 : (byte)0);

: fooobar.com/questions/635741/...

0

All Articles