C++ – Getting an array index (0,1,2,..8) from bit masking value (1,2,4,8..256) without using log2(n). Maybe a design issue

bitwise-operatorsc

I'm working on a component where I put in data and I get different data as a result. The input is always the same (3 Objects).
From these 3 Objects up to 9 other Objects can be calculated. One calculation for each output Object is performed.
Before the output data is calculated I want to set which of the 9 Objects shall be calculated.

  1. Set input data
  2. Set which output data shall be calculated
  3. Get Output data

I'm working in Visual C++ (C99). At the moment I'm facing a bit of a design problem here.
After I set the input data, I am using a bit mask to configure which output data is supposed to be calculated.

const int  foo1 = 1;   //000000001
const int  foo2 = 2;   //000000010
const int  foo3 = 4;   //000000100
const int  foo4 = 8;   //000001000
const int  foo5 = 16;  //000010000
const int  foo6 = 32;  //000100000
const int  foo7 = 64;  //001000000
const int  foo8 = 128; //010000000
const int  foo9 = 256; //100000000

SetOutput(foo2 | foo4 | foo5 );

The data is held in an array ARRAY[9] . For those that have been set (foo2, foo4 and foo5) the elements contain valid data after the calculation (ARRAY[2], ARRAY[4], ARRAY[5])

I then want to get the the resulting data.

GetData(foo2);
GetData(foo4);
GetData(foo5);

My problem is how do I get the element index from the mask values foo2 = 2, foo4 = 8 or for example foo5 = 16?
The only possibility would be taking log2(n) and get 2, 3 and 4, which would be the correct element indexes of ARRAY.

Is there a simpler way than this?
I thought about using a map instead, with the mask value (1,2,4,8…256) as key field and the calculated data in the value field.
But would prefer to keep the static array.
Thanks in advance!

Best Answer

An array with 257 entries will be fast, portable, and again fast. Many compilers provide a very fast built-in function to count leading or trailing zero bits in a number, for example __builtin_clz in gcc and Clang, which is likely about hundred times faster than a call to the log2 function.

Related Topic