I have a byte I’m using for bitflags. I know that one and only one bit in the byte is set at any give time.
Ex: unsigned char b = 0x20; //(00100000) 6th most bit set
I currently use the following loop to determine which bit is set:
int getSetBitLocation(unsigned char b) {
int i=0;
while( !((b >> i++) & 0x01) ) { ; }
return i;
}
How do I most efficiently determine the position of the set bit? Can I do this without iteration?
It is indeed possible.
You can try this algorithm. It splits the char in half to search for the top bit, shifting to the low half each time:
It uses two comparisons (three for
uint16s, four foruint32s…). and it might be faster than your loop. It is definitely not shorter.Based on the idea by Anton Kovalenko (hashed lookup) and the comment by 6502 (division is slow), I also suggest this implementation (8-bit => 3-bit hash using a de-Bruijn sequence)
or (larger LUT, but uses just three terms instead of four)