zoukankan      html  css  js  c++  java
  • 实战ffs函数

    这个函数是返回整形的最低位1的位置
    自己写是这个样子的:
    /* Find the first bit set in I.  */
    int lx_ffs(int i)
    {
    	int index = 0, ret = -1;
    	for(index = 0; index < sizeof(int) * 8; index ++)
    	{
    		if((1 << index) & i)
    		{
    			ret = index + 1;
    			break;
    		}
    	}
    
    	return ret;
    }

    
    
    人家库函数牛B,比较一次就可以得到
    其工作原理
    1=>位置1
    2=>位置2
    4=>位置3
    8=>位置4
    16=>位置5
    32=>位置6
    64=>位置7
    128=>位置8
    在得到最低位1的整数值后,根据数值得到所在位置
    /* Find the first bit set in I.  */
    int lx_ffs(int i)
    {
      static const unsigned char table[] =
    	{
    	  0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
    	  6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
    	  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
    	  7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
    	  8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
    	  8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
    	  8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
    	  8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
    	};
      unsigned int a;
      unsigned int x = i & -i;//这一步直接得到最低位1的整数值
    
      a = x <= 0xffff ? (x <= 0xff ? 0 : 8) : (x <= 0xffffff ?  16 : 24);
    
      return table[x >> a] + a;
    }

  • 相关阅读:
    计算机基础总结
    Apache安装错误 APR not found解决方法
    一、编译错误
    2.2 进程控制之进程共享
    2.1 进程控制之fork创建子进程
    ARM串口控制终端命令
    u-boot、kernel、root系统烧写和挂载命令命令
    8.1 编写USB鼠标驱动程序,并测试
    八、USB驱动分析
    Source Insight的使用
  • 原文地址:https://www.cnblogs.com/pangblog/p/3265461.html
Copyright © 2011-2022 走看看