#include <iostream>
using namespace std;
int findFirstBitOfInt(unsigned long word)
{
if(word == 0)
{
return -1;
}
int num = 0;
if ((word & 0xffff) == 0)
{
num += 16;
word >>= 16;
}
if ((word & 0xff) == 0)
{
num += 8;
word >>= 8;
}
if ((word & 0xf) == 0)
{
num += 4;
word >>= 4;
}
if ((word & 0x3) == 0)
{
num += 2;
word >>= 2;
}
if ((word & 0x1) == 0)
{
num += 1;
}
return num;
}
int main()
{
int a = 0, b = 1, c = 2, d = 4, e = 16;
cout<<findFirstBitOfInt(a)<<endl;
cout<<findFirstBitOfInt(b)<<endl;
cout<<findFirstBitOfInt(c)<<endl;
cout<<findFirstBitOfInt(d)<<endl;
cout<<findFirstBitOfInt(e)<<endl;
return 0;
}
运行程序输出:
-1
0
1
2
4