You are looking for x86 bit scan instructions
__inline__ size_t bsf(size_t input) { size_t pos; __asm__ ("bsf %1, %0" : "=r" (pos) : "rm" (input)); return pos; }
When using inline asm, make sure that both pos and input are the same storage class (2, 4, or 8 byte integers). This built-in function should not be a problem.
Most compilers have built-in functions that use this instruction, but MSVC is the only one I know that has a direct.
For the highest order bit set, use the bsr command bsr , the same syntax.
NOTE : if the input is 0 (no bit set), then the result will be undefined!
Here is the version that will put the predefined constant in pos if the input file is 0:
#define BIT_SCAN_IFZERO 0 __inline__ size_t bsf(size_t input) { size_t pos, ifzero = BIT_SCAN_IFZERO; __asm__ ( "bsf %1, %0\n\t" "cmovz %2, %0" : "=r" (pos) : "rm" (input) , "rm" (ifzero)); return pos; }
Define BIT_SCAN_IFZERO as you like. If you want a negative number, change size_t to ssize_t (type of signed size)
source share