1

从 bool[] 到 byte[]:将 bool[] 转换为 byte[]

但是我需要将 byte[] 转换为 List ,其中列表中的第一项是 LSB。

我尝试了下面的代码,但是当再次转换为字节并返回布尔值时,我得到了两个完全不同的结果......:

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

1 回答 1

6

您只考虑 7 位,而不是 8 位。这条指令:

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

应该:

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

无论如何,这是我将如何实现它:

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);
    }
}
于 2011-05-23T16:17:37.463 回答