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
Although I would probably only use this method if I absolutely required the best possible performance (e.g. for writing some sort of board game AI involving bitboards), the most efficient solution is to use inline ASM. See the Optimisations section of this blog post for code with an explanation.
[...], the
bsrl
assembly instruction computes the position of the most significant bit. Thus, we could use thisasm
statement:asm ("bsrl %1, %0" : "=r" (position) : "r" (number));