What\'s the fastest way to enumerate through an integer and return the exponent of each bit that is turned on? Have seen an example using << and another u
I guess bit shifting (<<) is the fastest.
Just for fun, here's a one-liner using LINQ.
It's certainly not the fastest way to do it, although it's not far behind the other answers that use yield
and iterator blocks.
int test = 42;
// returns 1, 3, 5
// 2^1 + 2^3 + 2^5
// = 2 + 8 + 32
// = 42
var exponents = Enumerable.Range(0, 32).Where(x => ((test >> x) & 1) == 1);
For a speedier solution I would probably return a plain collection rather than using an iterator block. Something like this:
int test = 2458217;
// returns 0, 3, 5, 6, 9, 15, 16, 18, 21
// 2^0 + 2^3 + 2^5 + 2^6 + 2^9 + 2^15 + 2^16 + 2^18 + 2^21
// = 1 + 8 + 32 + 64 + 512 + 32768 + 65536 + 262144 + 2097152
// = 2458217
var exponents = GetExponents(test);
// ...
public static List<int> GetExponents(int source)
{
List<int> result = new List<int>(32);
for (int i = 0; i < 32; i++)
{
if (((source >> i) & 1) == 1)
{
result.Add(i);
}
}
return result;
}