如何将 byte[] 转换为 BitArray,然后从 BitArray 中选取特定位

How to Convert byte[] to BitArray and then pick specific bits from the BitArray

我有一个包含以下内容的 BitArray:

byte[] myBytes = {0, 0, 2, 176, 168, 3, 19, 0};
BitArray myBitArr = new BitArray(myBytes); 

结果在 disp 上有些受人尊敬:(编辑:这不是问题)

00000000 00000000 01000000 00001101 00010101 11000000 11001000 00000000

敬畏,是:

00000000 000000**00 00000010 1011**0000 10101000 00000011 00010011 00000000

为了从 myBitArr 中取出位,我使用以下

bool[] myNumbers = GetBitSBiArray(myBitArr, 36, 50);

有了这个帮助方法

private static bool[] GetBitSBiArray(BitArray ba, int from, int to)
{
    bool[] temp = new bool[to - from];
    int t = 0;
    for (int i = ba.Length - to; i < ba.Length - from; i++)
    {
        temp[t] = ba.Get(i);
        t++;
    }
    return temp;
}

上面的方法returns不知何故错误的结果:

00010000 000000 (14bit) 

正确的结果是:

00000000 101011 (14bit) or 43

我暂时对溢出或其他异常不感兴趣。

我的方法有什么问题,我有什么替代方法?

其实我不知道你是怎么计算位的,位[36,50]是怎么变成“00000000 101011”的。但这是我的答案:我会这样写这样一个函数:

private static bool[] GetBitSBiArray(BitArray ba, int from, int to)
    {
        //from and to are zero-based
        //you can change it the way you prefer.

        if (to < from || to >= ba.Length)
            return null;

        List<bool> temp = new List<bool>();
        int t = 0;
        for (int i = from; i < to; i++)
            temp.Add(ba.Get(i));

        return temp.ToArray();
    }

问题是,你会陷入所有那些神秘的逆转中。 BitArraybyte[] 格式不适合你 byte[] 的格式,它在咬你。

看来你对数据的解读是"highest bit has index 0",最低位h。你需要映射到的是"highest bit is right, and every individual byte is lower endian".

我建议完全删除该辅助代码。问题是您使用错误的格式来初始化 BitArray - 显而易见的解决方案是修复输入,而不是为 "remap" 每次访问的索引创建辅助方法。

获得所需结果的最简单方法是

BitArray myBitArr = new BitArray(myBytes.Reverse().ToArray());

和方法

private static bool[] GetBitSBiArray(BitArray ba, int from, int to)
{
    bool[] temp = new bool[to - from];
    int t = 0;
    for (int i = from; i < to; i++)
    {
        temp[temp.Length - t - 1] = ba.Get(i);
        t++;
    }
    return temp;
}

想法是 Reverseing 字节数组将使各个字节中的位对齐(也就是说,您摆脱了每个单独字节中的 "reversed" 顺序),并且它将在一次操作中翻转位的顺序。

输出中 temp[temp.Length - t - 1] 的额外反转是为了匹配样本中的顺序 - 我认为这实际上是不必要的,因为那是你手动渲染的位,而不是你想要使用它们的顺序in. 如果你简单地使用 temp[t],第一个 bool 将对应于位 36,最后一个对应于位 50。这也意味着你可能不再需要使用你的辅助函数 - 只需使用 bitArray.Get(36) 获取第 36 位。