C#byte []到List <bool>

Nap*_*eon 1 c# byte boolean steganography

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

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

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

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];
    }
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 6

你只考虑7位,而不是8位.这条指令:

for (int i = 0; i < 7; i++)
Run Code Online (Sandbox Code Playgroud)

应该:

for (int i = 0; i < 8; i++)
Run Code Online (Sandbox Code Playgroud)

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)