c++c++11gccglibc

Standard way to call `ffsl` in C++?


The ffsl function is part of glibc. In GCC it is also available via __builtin_ffsl. It returns the index of the least significant bit in a long.

Is there a way to access this functionality in standards-conforming C++ code? I would like to get at these versions (if available) because they are written in assembly for high performance. (Most architectures provide an instruction for this function or similar.)


Solution

  • There is no standard function to achieve this and each compiler typically provides it's own intrinsic to compute ffs (see e.g. Wikipedia for relatively complete list). So your best take would be to do a wrapper

    #ifdef __GNUC__
    #  define ffs(x) __builtin_ffs(x)
    #elif __INTEL_COMPILER
    #  define ffs(x) _bit_scan_forward(x)
    ...
    

    Also note that __builtin_ffs and ffs(3) may generate non-equivalent code (I'd use compiler intrinsic as these tend to be better optimized by compiler, on the other hand GCC intrinsics are not always well optimized).