Ioragi
Ioragi

Reputation: 115

Byte array to bool array

I want to take in a byte [] and convert it to a bool []. I have found a code that places the bool in a bool queue, but I don't posses the necessary skill/knowledge to go from a method that gives me a bool queue to a method that gives me a bool array.

Any help is appreciated!

public void TmsTdiEnqueue(int bitCount, byte[] byteArray)
        {
            // New TAP bit queues with allocated number of bits
            boolQueue = new Queue<bool>(bitCount);

            // Fill bool queue
            int byteIndex = 0;
            int bitMask = 0x01;
            for (int i = 0; i < bitCount; i++)
            {
                boolQueue.Enqueue((tmsBytes[byteIndex] & bitMask) != 0);
                IncrementBitPointer(ref byteIndex, ref bitMask);
            }
        }

        private void IncrementBitPointer(ref int byteIndex, ref int bitMask)
        {
            byteIndex += (bitMask == 0x80) ? 1 : 0;
            bitMask = (bitMask == 0x80) ? 0x01 : bitMask << 1;
        }

Upvotes: 2

Views: 3896

Answers (2)

Dmitry
Dmitry

Reputation: 14059

If the source byte[] array has one boolean value per bit, you could simply use the BitArray class:

BitArray ba = new BitArray(new byte[] { 1, 2, 3 });
bool[] ret = new bool[ba.Length];
ba.CopyTo(ret, 0);

Upvotes: 6

Sean
Sean

Reputation: 62472

You can use SelectMany to do this. First, start with a method that converts a single byte to an array of bool:

static bool[] ByteToBools(byte value)
{
    var values = new bool[8];

    values[0] = (value & 1) == 0 ? false : true;
    values[1] = (value & 2) == 0 ? false : true;
    values[2] = (value & 4) == 0 ? false : true;
    values[3] = (value & 8) == 0 ? false : true;
    values[4] = (value & 16) == 0 ? false : true;
    values[5] = (value & 32) == 0 ? false : true;
    values[6] = (value & 64) == 0 ? false : true;
    values[7] = (value & 128) == 0 ? false : true;

    return values;
}

Now we just SelectManyover thebyte array, and for each byte we call ByteToBools:

var numbers = new byte[]{1, 2, 3, 5, 255};

var bits = numbers.SelectMany(number => ByteToBools(number));
foreach(var bit in bits)
{
    Console.WriteLine(bit);
}

Upvotes: 1

Related Questions