Joan Gerard
Joan Gerard

Reputation: 125

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);
}

Upvotes: 3

Views: 4141

Answers (3)

Tom 7
Tom 7

Reputation: 527

This is now part of the standard library in C++20. It can be found as std::countr_zero, in the header <bit>. See https://en.cppreference.com/w/cpp/numeric/countr_zero.

#include <bit>
#include <iostream>

int main() {
  int value = 12;
  cout << std::countr_zero(value);

  return 0;
}

Upvotes: 0

fuz
fuz

Reputation: 93034

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.

Upvotes: 3

zneak
zneak

Reputation: 138061

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 a list 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.

Upvotes: 6

Related Questions