zoukankan      html  css  js  c++  java
  • 理解__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
    ", a, clz(a));
    21 
    22     a=1;
    23     printf("0x%x ret=%d
    ", a, clz(a));
    24 
    25     a=2;
    26     printf("0x%x ret=%d
    ", a, clz(a));
    27 
    28     a=4;
    29     printf("0x%x ret=%d
    ", a, clz(a));
    30 
    31     a=8;
    32     printf("0x%x ret=%d
    ", a, clz(a));
    33 
    34     a=16;
    35     printf("0x%x ret=%d
    ", a, clz(a));;
    36 
    37     a=0x0FFFFFFF;
    38     printf("0x%x ret=%d
    ", a, clz(a));
    39 
    40     a=0x1FFFFFFF;
    41     printf("0x%x ret=%d
    ", a, clz(a));
    42 
    43     a=0x2FFFFFFF;
    44     printf("0x%x ret=%d
    ", a, clz(a));
    45 
    46     a=0x4FFFFFFF;
    47     printf("0x%x ret=%d
    ", a, clz(a));
    48 
    49     a=0x8FFFFFFF;
    50     printf("0x%x ret=%d
    ", a, clz(a));
    51 
    52     a=0xFFFFFFFF;
    53     printf("0x%x ret=%d
    ", 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;
        type |=1; //防止type为0时,出现无限循环infinite loop,type为0时的计算结果为31。
        while(!(type & 0x80000000)) //检测最高位是不是1。
        {
            num +=1;
            type <<= 1;
        }
        return num;
    }

    完。

  • 相关阅读:
    MVC3 缓存应用
    centos下安装tomcat
    VS2010安装完SP1后再安装Silverlight Tools 4遇到的问题解决办法
    TOMCAT多站点配置
    C#.NET 添加图片水印
    装了vs11后运行MVC3程序出问题
    ASP.NET Session的七点认识
    C# 用正则取文本中所有链接
    Long time no blog...
    从程序员到项目经理(二)
  • 原文地址:https://www.cnblogs.com/liyou-blog/p/4191146.html
Copyright © 2011-2022 走看看