ในคอมไพเลอร์ GCC มีฟังก์ชัน Built-in ต่างๆ ดังนี้
ฟังก์ชัน __builtin_popcount(x)
ใช้นับจำนวนบิต 1 ในข้อมูลจำนวนเต็ม
ตัวอย่าง
#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;
}ผลลัพธ์
Count of 1s in binary of 13 is 3
ฟังก์ชัน __builtin_parity(x)
ตรวจสอบความเป็นคู่คี่ของจำนวนบิต 1 คืนค่า true ถ้าเป็นคี่ false ถ้าเป็นคู่
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int n = 13; // 1101
cout << "Parity of " << n << " is " << __builtin_parity(n);
return 0;
}ผลลัพธ์
Parity of 13 is 1
ฟังก์ชัน __builtin_clz(x)
นับจำนวนศูนย์นำหน้า (Leading Zeros) ของจำนวนเต็ม
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int n = 13; // 1101 -> 0000...00001101 (32-bit)
cout << "Leading zero count of " << n << " is " << __builtin_clz(n);
return 0;
}ผลลัพธ์
Leading zero count of 13 is 28
ฟังก์ชัน __builtin_ctz(x)
นับจำนวนศูนย์ท้าย (Trailing Zeros) ของจำนวนเต็ม
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int n = 12; // 1100 -> 0000...00001100 (32-bit)
cout << "Trailing zero count of " << n << " is " << __builtin_ctz(n);
return 0;
}ผลลัพธ์
Trailing zero count of 12 is 2