If I have some integer n, and I want to know the position of the most significant bit (that is, if the least significant bit is on the right, I want to know the position of the furthest left bit that is a 1), what is the quickest/most efficient method of finding out?
I know that POSIX supports a ffs()
method in strings.h to find the first set bit, but there doesn't seem to be a corresponding fls()
method.
Is there some really obvious way of doing this that I'm missing?
What about in cases where you can't use POSIX functions for portability?
Edit: What about a solution that works on both 32 and 64 bit architectures (many of the code listings seem like they'd only work on 32 bit ints).
Note that what you are trying to do is calculate the integer log2 of an integer,
Observe that you can attempt to search more than 1 bit at a time.
This approach uses a binary search
Another binary search method, perhaps more readable,
And because you will want to test these,
The code:
Or get the integer part of FPU instruction FYL2X (Y*Log2 X) by setting Y=1
GCC has:
I'd expect them to be translated into something reasonably efficient for your current platform, whether it be one of those fancy bit-twiddling algorithms, or a single instruction.
A version in C using successive approximation:
Advantage: the running time is constant regardless of the provided number, as the number of loops are always the same. ( 4 loops when using "unsigned int")
I had a need for a routine to do this and before searching the web (and finding this page) I came up with my own solution basedon a binary search. Although I'm sure someone has done this before! It runs in constant time and can be faster than the "obvious" solution posted, although I'm not making any great claims, just posting it for interest.
Some overly complex answers here. The Debruin technique should only be used when the input is already a power of two, otherwise there's a better way. For a power of 2 input, Debruin is the absolute fastest, even faster than
_BitScanReverse
on any processor I've tested. However, in the general case,_BitScanReverse
(or whatever the intrinsic is called in your compiler) is the fastest (on certain CPU's it can be microcoded though).If the intrinsic function is not an option, here is an optimal software solution for processing general inputs.
Note that this version does not require a Debruin lookup at the end, unlike most of the other answers. It computes the position in place.
Tables can be preferable though, if you call it repeatedly enough times, the risk of a cache miss becomes eclipsed by the speedup of a table.
This should produce the highest throughput of any of the software answers given here, but if you only call it occasionally, prefer a table-free solution like my first snippet.