简体   繁体   English

c++ 中的“ctz”命令必须使用什么库?

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

Is there a library for 'count trailing zeroes'(ctz command)?是否有用于“计数尾随零”(ctz 命令)的库?
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. C/C++ 标准库不提供该操作。 There are, however, compiler-specific intrinsics for most of this kind of bitwise operations.但是,对于大多数此类按位运算,都有特定于编译器的内在函数。

With gcc/clang, it's __builtin_ctz .使用 gcc/clang,它是__builtin_ctz You don't need any #include to use it, precisely because it's an intrinsic command.您不需要任何#include 来使用它,正是因为它是一个内在命令。 There's alist of GCC intrinsics here , and a list of Clang intrinsics here.这里有一个GCC 内在函数列表,这里有一个Clang 内在函数列表

With Visual Studio, you need to #include <intrin.h> , and use _BitScanReverse as shown in this answer .使用 Visual Studio,您需要#include <intrin.h>并使用_BitScanReverse如本答案所示

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 :在 POSIX 上,您还可以使用<strings.h> (而不是<string.h> !)中的ffs (查找第一组)函数,该函数记录为

 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. ffs()函数应在i中找到第一个位集(从最低有效位开始),并返回该位的索引。 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:请注意,此函数是 XSI 扩展的一部分,因此您应该在包含<strings.h>或任何系统头文件之前设置_XOPEN_SOURCE功能测试宏,以便原型可见:

#define _XOPEN_SOURCE 700
#include <strings.h>

gcc recognizes ffs and compiles it into a bsf instruction on x86. gcc 识别ffs并将其编译为 x86 上的bsf指令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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