C# byte[] to List<bool>

﹥>﹥吖頭↗ 提交于 2019-12-11 08:55:27

问题


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];
    }

回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/6099920/c-sharp-byte-to-listbool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!