C++ 中 GCC 编译器的内置函数

c++server side programmingprogramming

GCC 编译器中有一些内置函数。这些函数如下所示。

函数 _builtin_popcount(x)

此内置函数用于计算整数类型数据中 1 的数量。让我们看一个 _builtin_popcount() 函数的示例。

示例

#include<iostream>
using namespace std;
int main() {
   int n = 13; //二进制为 1101
   cout << "Count of 1s in binary of <<< n <<" is " << __builtin_popcount(n);
   return 0;
}

输出

13 的二进制数中 1 的个数为 3

函数 _builtin_parity(x)

此内置函数用于检查数字的奇偶性。如果数字具有奇偶性,则返回 true,否则返回 false。让我们看一个 _builtin_parity() 函数的示例。

示例

#include<iostream>
using namespace std;
int main() {
   int n = 13; //二进制为 1101
   cout << "<< n <<"< 的奇偶性为<<< __builtin_parity(n);
   return 0;
}

输出

13 的奇偶性为 1

函数 _builtin_clz(x)

此内置函数用于计算整数的前导零。clz 代表计数前导零。让我们看一个 _builtin_clz() 函数的示例。

示例

#include<iostream>
using namespace std;
int main() {
   int n = 13; //二进制为 1101
   //0000 0000 0000 0000 0000 0000 0000 0000 1101(32 位整数)
   cout << "< n <<" 的前导零计数为 <<< __builtin_clz(n);
   return 0;
}

输出

13 的前导零计数为 28

函数 _builtin_ctz(x)

此内置函数用于计算整数的尾随零。ctz 代表计数尾随零。让我们看一个 _builtin_ctz() 函数的示例。

示例

#include<iostream>
using namespace std;
int main() {
   int n = 12; //二进制为 1100
   //0000 0000 0000 0000 0000 0000 0000 0000 1100 (32 位整数 )
   cout << "<< n <<"<< 的尾随零计数为 <<< __builtin_ctz(n);
   return 0;
}

输出

12 的尾随零计数为 2

相关文章