C/C++ __builtin 超实用位运算函数总结

发布时间 2023-11-07 20:30:53作者: 逆行伐仙

以 __builtin 开头的函数,是一种相当神奇的位运算函数,下面本人盘点了一下这些以 __builtin 开头的函数,希望可以帮到大家。

1 __builtin_ctz( ) / __buitlin_ctzll( )

用法:返回括号内数的二进制表示数末尾0的个数

//eg:
#include<bits/stdc++.h>
using namespace std ;

int main(){
    cout << __builtin_ctz(8) << endl ;
    return 0 ;
}

 

输出:3
8 = 1000 , 末尾有3个0

2 __buitlin_clz( ) / __buitlin_clzll( )

用法:返回括号内数的二进制表示数前导0的个数

//eg:
#include<bits/stdc++.h>
using namespace std ;

int main(){
    cout << __builtin_clz(8) << endl ;
    return 0 ;
}

 

输出:28
8 = 0000 0000 0000 0000 0000 0000 0000 1000 , 整型(int)为32位,有28个前导0

换位long long后

#include<bits/stdc++.h>
using namespace std ;

int main(){
    cout << __builtin_clzll(8) << endl ;
    return 0 ;
}

 

输出:60
长整型(long long)为64位,有60个前导0

3 __builtin_popcount( )

用法:返回括号内数的二进制表示数1的个数

//eg:
#include<bits/stdc++.h>
using namespace std ;

int main(){
    cout << __builtin_popcount(15) << endl ;
    return 0 ;
}

 

输出:4
15 = 1111 , 1的个数位4

4 __builtin_parity( )

用法:判断括号中数的二进制表示数1的个数的奇偶性(偶数返回0 , 奇数返回0)

#include<bits/stdc++/h>
using namespace std ;

int main(){
    cout << __builtin_parity(15) << endl ;
    return 0 ;
}

 

输出:0
15 = 1111, 1的个数为4(偶数个)

5 __builtin_ffs( )

用法:返回括号中数的二进制表示数的最后一个1在第几位(从后往前算)

//eg:
#include<bits/stdc++.h>
using namespace std ;

int main(){
    cout << __builtin_ffs(8) << Lendl ;
    return 0 ;
}

 

输出:4
8 = 1000 , 最后一个1在第四位

6 __builtin_sqrt( )

7 __builtin_sqrtf( )

用法:快速开平方

//eg:
#include<bits/stdc++.h>
using namespace std ;

int main(){
    cout << __builtin_sqrt(16) << endl ;
    cout << __builtin_sqrtf(16) << endl ;
    cout << sqrt(16) << endl ;
    return 0 ;
}

 

输出:4
sqrt(16) = 4
那么他们跟 sqrt() 有什么区别呢?
做个小测试: 从到从1到108 比较耗时:
sqrt: 约 3700 ms
__builtin_sqrt( ): 约 330 ms
__bulitin_sqrtf( ): 约 360ms
快了接近10倍!
那么这两个函数的区别是什么呢?
__builtin_sqrt( ) :8位
__builtin_sqrtf( ) :4位