Builtin function

发现 Builtin function 可以用来计算十进制数中1的个数;返回1的个数是奇数还是偶数;返回开头0的个数;返回结尾0的个数。

参考链接:

// C program to illustrate _builtin_popcount(x) 

#include <stdio.h> 
int main() 
{ 
    int n = 5; 
    printf("Count of 1s in binary of %d is %d ", 
        n, __builtin_popcount(n)); 
    return 0; 
} 

// C program to illustrate _builtin_parity(x) 

#include <stdio.h> 
int main() 
{ 
    int n = 7; 
    printf("Parity of %d is %d ", 
        n, __builtin_parity(n)); 
    return 0; 
} 

第二个函数 _builtin_parity(x) 是用来计算:x中1的个数是奇数个则返回1,否则返回0.

// C program to illustrate __builtin_clz(x) 
#include <stdio.h> 
int main() 
{ 
    int n = 16; 
    printf("Count of leading zeros before 1 in %d is %d", 
        n, __builtin_clz(n)); 
    return 0; 
} 

// C program to illustrate __builtin_ctz(x) 
#include <stdio.h> 
int main() 
{ 
    int n = 16; 
    printf("Count of zeros from last to first "
        "occurrence of one is %d", 
        __builtin_ctz(n)); 
    return 0; 
} 

// C program to illustrate builtin functions of 
// GCC compiler 
#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int num = 4; 
    int clz = 0; 
    int ctz = 0; 
    int pop = 0; 
    int parity = 0; 

    pop = __builtin_popcount(num); 
    printf("Number of one's in %d is %d\n", num, pop); 

    parity = __builtin_parity(num); 
    printf("Parity of %d is %d\n", num, parity); 

    clz = __builtin_clz(num); 
    printf("Number of leading zero's in %d is %d\n", num, clz); 

    // It only works for unsigned values 
    clz = __builtin_clz(-num); 
    printf("Number of leading zero's in %d is %d\n", -num, clz); 

    ctz = __builtin_ctz(num); 
    printf("Number of trailing zero's in %d is %d\n", num, ctz); 

    return 0; 
} 

 

posted @ 2019-08-01 13:56  爱学英语的程序媛  阅读(385)  评论(0编辑  收藏  举报