追代码的时候看见一个求最高位1是哪一位的算法,比较适合学习,给大家分享一下。
static int fls(int x)
{
int r = 32;
if (!x)
return 0;
if (!(x & 0xffff0000u)) {
printf("-16\n");
x <<= 16;
r -= 16;
}
if (!(x & 0xff000000u)) {
printf("-8\n");
x <<= 8;
r -= 8;
}
if (!(x & 0xf0000000u)) {
printf("-4\n");
x <<= 4;
r -= 4;
}
if (!(x & 0xc0000000u)) {
printf("-2\n");
x <<= 2;
r -= 2;
}
if (!(x & 0x80000000u)) {
printf("-1\n");
x <<= 1;
r -= 1;
}
return r;
}
测试:
fls(0x80000000) = 32
fls(0x11000000 ) = 29
如果要取64位数据最高位1的位数的话:
static int fls64(unsigned long x)
{
unsigned int h = x >> 32;
if (h)
return fls(h) + 32;
return fls(x);
}
测试:
fls64(0x9000000000000000 ) = 64
fls64(0x1000000000000000 ) = 61