简体   繁体   中英

what library do I have to use for 'ctz' command in c++?

Is there a library for 'count trailing zeroes'(ctz command)?
What is the procedure for do that?

I tried:

#include<iostream>
using namespace std;
int main()
{
    int value = 12;
    cout<<ctz(value);
}

C/C++ standard libraries don't offer that operation. There are, however, compiler-specific intrinsics for most of this kind of bitwise operations.

With gcc/clang, it's __builtin_ctz . You don't need any #include to use it, precisely because it's an intrinsic command. There's alist of GCC intrinsics here , and a list of Clang intrinsics here.

With Visual Studio, you need to #include <intrin.h> , and use _BitScanReverse as shown in this answer .

If you want to make your code portable across compilers, you're encouraged to provide your own macros/wrappers.

On POSIX, you can also use the ffs (find first set) function from <strings.h> (not <string.h> !) which is documented as :

 int ffs(int i);

The ffs() function shall find the first bit set (beginning with the least significant bit) in i , and return the index of that bit. Bits are numbered starting at one (the least significant bit).

Note that this function is part of the XSI extensions, so you should set the _XOPEN_SOURCE feature test macro before including <strings.h> or any system headers, so the prototype is visible:

#define _XOPEN_SOURCE 700
#include <strings.h>

gcc recognizes ffs and compiles it into a bsf instruction on x86.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM