Efficient bitmask enumeration in C

80 views Asked by At

Say I have some bitmask, such as int b=0b1010110. Having another int m, there are 2^4=16 options on what m & b can be: the values of bits 1,2,4,6 of m & b can be all either 0 or 1 while all other values are 0.

I want to extract an integer between 0 and 15 from m & b as efficiently as possible, thereby discarding all the 0-bits in b.

It is easy to do in O(B) time (where b has B bits set) by just checking the specific bits of m. I want this to work independently of b, so no hard-coding of the bits of b. The bits of b are also available in an array.

Is there a bit-operation to do this faster, in O(1) or O(log B) or so?

0

There are 0 answers