开发者

Get Positive Bits Indexes from Bit Array

开发者 https://www.devze.com 2023-02-24 18:08 出处:网络
Say I have the following BitArray combinedResults = searchBitArray.And(genreBitArray); Which contains positive bits i.e 100100110000

Say I have the following BitArray combinedResults = searchBitArray.And(genreBitArray);

Which contains positive bits i.e 100100110000

How can I get the开发者_如何学运维 indexes of all the positive ones ?


Here's a first, decidedly ghetto, crack at it:

BitArray ba = new BitArray(new bool[] {true,false,false,true,false,false,true,true,false,false,false,false});
List<int> pos = new List<int>();
for (int i = 0; i < ba.Length; i++)
{
    if (ba[i])
        pos.Add(i);
}

That would give you a list containing 0, 3, 6, 7. You could start at ba.Length - 1 and decrement down to zero if you need to read from right to left.

edit: Wrapped in an extension method, just because:

void Main()
{
    BitArray ba = new BitArray(new bool[] {true,false,false,true,false,false,true,true,false,false,false,false});

    List<int> positives = ba.GetBitPositions(true);
    List<int> negatives = ba.GetBitPositions(false);
}

public static class BitArrayExtensions
{
    public static List<int> GetBitPositions(this BitArray ba, bool MatchCondition)
    {
        List<int> pos = new List<int>();

        for (int i = 0; i < ba.Length; i++)
        {
            if (ba[i] == MatchCondition)
                pos.Add(i);
        }

        return pos;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消