I have an array of nine elements and an integer. Using the integer and bitmasking I want to save information about whether an element of the array is valid.
So my question is: Is there a simpler way than using log2() of math.h to get from my bitmask to my array element number?
For example, I store foo2,
foo4
and foo5
in mValue
using bitmasking.
Then I want to get the array element at position foo2 = 2
, which is the second bit, so the 2nd array element, which is 34
.
But the only way I can think of is the log2(n)
funtion.
Is there a simpler one using bitshifting maybe?
Simply put, I want to do this:
Is the nth bit of an integer mValue
set to 1? then get me the nth element of an array bar
.
#include <math.h>
const int foo1 = 1;
const int foo2 = 2;
const int foo3 = 4;
const int foo4 = 8;
const int foo5 = 16;
int bar[9] = {23,34,82,8,7,0,23,19,20};
int mValue;
void SetValue(int nVal)
{
mValue = nVal;
}
bool IsElementValid(int nVal)
{
return mValue & nVal;
}
int main()
{
SetValue(foo2 | foo4 | foo5 );
IsElementValid(foo4); //true
IsElementValid(foo5); //true
IsElementValid(foo1); //false
//access array element 1 with value foo2 (2)
if(IsElementValid(foo2))
printf("%d\n", bar[log2(foo2)]); // output: '34'
}