实战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;
}

你可能感兴趣的:(实战ffs函数)