views:

629

answers:

5

Hello,

Is there a simple way to convert a bitmask in to an array index?

ie. If i've got an enum

a = 0x01,
b = 0x02,
c = 0x04,
d = 0x08,
e = 0x10, 
etc

and I want to store releated data in an array, is there a simple way such that i can convert a to 0, b to 1, c to 2. etc?

Many thanks

+1  A: 

I dont know a simple solution like you asked for, but why not just use a map instead an array?

Should work without any magic conversion.

StefanB
+3  A: 

Log2 n?

lc
+3  A: 

I'm not sure if this is what you're asking, but why don't you just take a 2-base log?

Can Berk Güder
Ah yes, natural log. That's what I was looking for. I thought there'd be something, just couldn't remeber what it was. Cheers.
Dynite
That's not a natural log. A natural log is log base e.
Can Berk Güder
Yes, I found out my error when i got 1.3 instead of 2 :).
Dynite
+5  A: 
r =   ln base 2 
and programmatically,

unsigned int v=yourEnumValue;
unsigned r = 0; 
while (v >>= 1) 
{
   r++;
}

r is your answer
lakshmanaraj
Exactly what I was thinking.
jrockway
+1  A: 

Use a std::map:

#include <map>

std::map <my_enum, my_datatype> m;
m[ a ] = whatever;
anon
I don't want to use a map, as i dont want the overhead of storing the key.
Dynite
The overhead for an enum would be tiny - and you have to compare it with the overhead of calculating the index.
anon