Dynite
Dynite

Reputation: 2383

Bitmask to Array Index

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

Upvotes: 4

Views: 4794

Answers (5)

anon
anon

Reputation:

Use a std::map:

#include <map>

std::map <my_enum, my_datatype> m;
m[ a ] = whatever;

Upvotes: 2

lakshmanaraj
lakshmanaraj

Reputation: 4175

r =   ln base 2 
and programmatically,

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

r is your answer

Upvotes: 6

Can Berk G&#252;der
Can Berk G&#252;der

Reputation: 113380

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

Upvotes: 4

lc.
lc.

Reputation: 116528

Log2 n?

Upvotes: 3

StefanB
StefanB

Reputation: 286

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.

Upvotes: 2

Related Questions