Question

From bool[] to byte[]: Convert bool[] to byte[]

But I need to convert a byte[] to a List where the first item in the list is the LSB.

I tried the code below but when converting to bytes and back to bools again I have two totally different results...:

public List<bool> Bits = new List<bool>();


    public ToBools(byte[] values)
    {
        foreach (byte aByte in values)
        {
            for (int i = 0; i < 7; i++)
            {
                Bits.Add(aByte.GetBit(i));
            }
        }
    }



    public static bool GetBit(this byte b, int index)
    {
        if (b == 0)
            return false;

        BitArray ba = b.Byte2BitArray();
        return ba[index];
    }
Was it helpful?

Solution

You're only considering 7 bits, not 8. This instruction:

for (int i = 0; i < 7; i++)

Should be:

for (int i = 0; i < 8; i++)

Anyway, here's how I would implement it:

byte[] bytes = ...
List<bool> bools = bytes.SelectMany(GetBitsStartingFromLSB).ToList();

...

static IEnumerable<bool> GetBitsStartingFromLSB(byte b)
{
    for(int i = 0; i < 8; i++)
    {
        yield return (b % 2 == 0) ? false : true;
        b = (byte)(b >> 1);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top