Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert bool [] into byte []

Tags:

c#

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

  • byte[0]=0xFB
  • byte[1]=AC
  • etc
like image 379
Himanshu Bajpai Avatar asked Jan 24 '12 12:01

Himanshu Bajpai


2 Answers

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();
like image 72
Jon Skeet Avatar answered Oct 16 '22 00:10

Jon Skeet


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.

Edit:

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);
like image 28
Guffa Avatar answered Oct 16 '22 01:10

Guffa