Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

gcc

c++11

glibc

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.)

like image 741
Dan R Avatar asked Oct 21 '25 04:10

Dan R


2 Answers

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).

like image 120
yugr Avatar answered Oct 22 '25 16:10

yugr


In C++20 there is std::countr_zero that can be used instead of the builtin.

like image 43
dened Avatar answered Oct 22 '25 18:10

dened



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!