C++ 語言中的 GCC 編譯器的內建函式


GCC 編譯器中有一些內建函式。這些函式如下。

函式 _builtin_popcount(x)

此內建函式用於計算整數型別資料中 1 的個數。我們來看一個 _builtin_popcount() 函式的示例。

示例

 線上演示

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

輸出

Count of 1s in binary of 13 is 3

函式 _builtin_parity(x)

此內建函式用於檢查一個數字的奇偶性。如果該數字具有奇偶性,它將返回 true,否則將返回 false。我們來看一個 _builtin_parity() 函式的示例。

示例

 線上演示

#include<iostream>
using namespace std;
int main() {
   int n = 13; //The binary is 1101
   cout << "Parity of "<< n <<" is " << __builtin_parity(n);
   return 0;
}

輸出

Parity of 13 is 1

函式 _builtin_clz(x)

此內建函式用於計算整數的前導零的個數。clz 表示 Count Leading Zeros。我們來看一個 _builtin_clz() 函式的示例。

示例

 線上演示

#include<iostream>
using namespace std;
int main() {
   int n = 13; //The binary is 1101
   //0000 0000 0000 0000 0000 0000 0000 1101 (32bit integer )
   cout << "Leading zero count of "<< n <<" is " << __builtin_clz(n);
   return 0;
}

輸出

Leading zero count of 13 is 28

函式 _builtin_ctz(x)

此內建函式用於計算整數的字尾零的個數。ctz 表示 Count Trailing Zeros。我們來看一個 _builtin_ctz() 函式的示例。

示例

 線上演示

#include<iostream>
using namespace std;
int main() {
   int n = 12; //The binary is 1100
   //0000 0000 0000 0000 0000 0000 0000 1100 (32bit integer )
   cout << "Trailing zero count of "<< n <<" is " << __builtin_ctz(n);
   return 0;
}

輸出

Trailing zero count of 12 is 2

更新於:2019-07-30

505 瀏覽

開啟你的 職業生涯

完成課程並獲得證書

開始
廣告
© . All rights reserved.