Radik Harutyunyan
Radik Harutyunyan

Reputation: 13

Get index of a 1 in a bitarray?

Friends, who know how can I get an index of a 1 in a Bitarray and push it to an array. some functions or something else

I have an Uint16 , here I want to read bits from this variable and get indexes of 1 and put it to an array or list

Upvotes: 1

Views: 2212

Answers (3)

apocalypse
apocalypse

Reputation: 5884

Step 1, prepare your BitArray:

 var bits = new BitArray (new[] { false, true, false, false, true, false, false });

Step 2, change it to form for you understandable (List, 1=true, 0=false)

 var list = bits.Cast<bool> ().Select (x => x ? 1 : 0).ToList ();

Step 3, now you can use IndexOf which you already know

 int index = list.IndexOf (1); // index=1, it looks from left ot right

If you want to search form right to left, use Reverse() method on your list.

It is not optimal solution, but I think it is most easy to understand for you.

EDIT:

var bits = new BitArray (new[] { false, true, false, false, true, false, false });

var bitsWithIndex = bits.Cast<bool> () // we need to use Cast because BitArray does not provide generic IEnumerable
                        .Select ((bit, index) => new { Bit = bit, Index = index}); // projection, we will save bit indices

// now we will get indices of all true(1) bits [from left to right]
var indices = bitsWithIndex.Where (x => x.Bit == true).Select (x => x.Index).ToArray ();

Upvotes: 1

Khiem Tran
Khiem Tran

Reputation: 6169

You have an UInt16, you need to read indexes of bit 1 then:

List<int> GetIndexes(int number) 
{
     var result = new List<int>();
     var index = 0;
     while (number > 0) 
     {
         if (number & 1) 
         {
              result.Add(index);
         } 
         index ++;
         number >= 1;
     }

     return result;
}

Upvotes: 0

Patrick Artner
Patrick Artner

Reputation: 51683

You query each position of the bitarray and report the indexes. You could use simple for loop and accumulate your true indexes in a List - I choose linq, looks nices:

using System.Linq;
using System.Collections;

public static IEnumerable<int> GetTrueIndexes(BitArray arr)
{
    if (arr != null)        
        return Enumerable.Range(0,arr.Count).Where( idx => arr.Get(idx));

    return new int[0];
}


public static void Main()
{
    BitArray b = new BitArray(
        "100101010000101"
        .Select(c => c == '0' ? false : true )
        .ToArray());

    var trueIndexes =  GetTrueIndexes(b);       

    System.Console.WriteLine(string.Join(", ",trueIndexes)); 
}

Output:

0, 3, 5, 7, 12, 14

Upvotes: 0

Related Questions