【问题标题】:C# byte[] to List<bool>C# byte[] 到 List<bool>
【发布时间】:2023-03-21 18:42:02
【问题描述】:

从 bool[] 到 byte[]:Convert bool[] to 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];
    }

【问题讨论】:

  • 有什么理由不使用BitArray Class 来表示整个字节数组而不是每个单字节?

标签: c# byte boolean steganography


【解决方案1】:

您只考虑 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);
    }
}

【讨论】:

    猜你喜欢
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 2015-08-06
    • 2022-11-15
    • 2012-08-27
    • 1970-01-01
    • 2010-12-06
    相关资源
    最近更新 更多