Re: testing if just one bit is set...
..rhavin grobert wrote:
guess you have a processor that can handle 32bit natively and you have
a 32-bit-int. im now looking for some *ultrafast* way to determine if
an int has more than one bit set. any ideas?
I think the "binary search" method is quick enough, but you will need to
measure it. Something like
inline bool moreThanOneBitSet(unsigned value,
unsigned mask1, unsigned mask2)
{
return (value & mask1) && (value & mask2);
}
bool moreThanOneBitSet(unsigned value)
{
static const unsigned masks[] = { 0x0000FFFF,0xFFFF0000,
0x00FF00FF,0xFF00FF00,
0x0F0F0F0F,0xF0F0F0F0,
0x33333333,0xCCCCCCCC,
0x55555555,0xAAAAAAAA };
if (value > 0) {
return moreThanOneBitSet(value, masks[0], masks[1]) ||
moreThanOneBitSet(value, masks[2], masks[3]) ||
moreThanOneBitSet(value, masks[4], masks[5]) ||
moreThanOneBitSet(value, masks[6], masks[7]) ||
moreThanOneBitSet(value, masks[8], masks[9]);
}
else
return false;
}
At most, 10 bitwise AND, 5 logical AND, 5 logical OR, and not sure how
many tests against 0 and jumps...
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask