Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the index of the left-most 1 bit for x=2^k? [duplicate]

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.

like image 804
abcdabcd987 Avatar asked Jan 25 '26 12:01

abcdabcd987


1 Answers

Many CPUs have a native hardware instruction, something like CTZ ("count trailing zeros"). GCC ex­po­ses this through the built-in function __builtin_ctz; other compilers should have similar facilities.

like image 66
Kerrek SB Avatar answered Jan 28 '26 04:01

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!