首页 > 代码库 > 理解__builtin_clz特性

理解__builtin_clz特性

a.c:

 1 /*************************************************************************                                                                2     * File: a.c 3     * Brief: 4     * Author: 5     * Mail: 6     * Created Time: Mon Dec 29 09:28:35 2014 7  ************************************************************************/ 8  9 #include<stdio.h>10 11 int clz(unsigned int a)12 {13     return __builtin_clz(a);14 }15 16 int main()17 {18     unsigned int a=0;19     a=0;20     printf("0x%x ret=%d\n", a, clz(a));21 22     a=1;23     printf("0x%x ret=%d\n", a, clz(a));24 25     a=2;26     printf("0x%x ret=%d\n", a, clz(a));27 28     a=4;29     printf("0x%x ret=%d\n", a, clz(a));30 31     a=8;32     printf("0x%x ret=%d\n", a, clz(a));33 34     a=16;35     printf("0x%x ret=%d\n", a, clz(a));;36 37     a=0x0FFFFFFF;38     printf("0x%x ret=%d\n", a, clz(a));39 40     a=0x1FFFFFFF;41     printf("0x%x ret=%d\n", a, clz(a));42 43     a=0x2FFFFFFF;44     printf("0x%x ret=%d\n", a, clz(a));45 46     a=0x4FFFFFFF;47     printf("0x%x ret=%d\n", a, clz(a));48 49     a=0x8FFFFFFF;50     printf("0x%x ret=%d\n", a, clz(a));51 52     a=0xFFFFFFFF;53     printf("0x%x ret=%d\n", a, clz(a));54 55     return 0;56 }57          

测试结果如下:

技术分享

注意,a=0的时候,__builtin_cl返回的值和a=1的情况一样,都是是31位。

好奇怪,查到gcc官网上说(https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html):

— Built-in Function: int __builtin_clz (unsigned int x)Returns the number of leading 0-bits in x, starting at the most significant bit position. If x is 0, the result is undefined.

也就是说,a=0的情况,这个函数是不会理会这种情况的。

 

下面我实现一个vc版本的:

int builtin_clz(unsigned int type){    int num = 0;    while(!(type & 0x80000000)) //检测最高位是不是1.    {        num +=1;        type <<= 1;    }    return num;}

 

完。

 

理解__builtin_clz特性