Possible Duplicate:
Efficient bitwise operations for counting bits or find the right|left most ones
I wrote a search algorithm. In order to optimize it, I want to use a 32bit int to mark if number 0~31 could be used. That is, if I have a state State, I could easily fetch all possible number by using:
x = State & -State
State -= x
But actually, I need to know where is the 1 in x (notice that there is only 1 in x's binary form)? For example, if x = 0000 0100, I want to know that is the third.
I know I could do that by using a for loop, but it seems that it would cost much time.
I wonder that if there is a method using bitwise operation? And would static_cast<int>(log2(x)) costs much time?
Thanks for any help.
Many CPUs have a native hardware instruction, something like CTZ ("count trailing zeros"). GCC exposes this through the built-in function __builtin_ctz; other compilers should have similar facilities.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With