//#include <bitops.h>
#include <stdio.h>
static __always_inline int fls(int x)
{
int r = 32;
if (!x)
return 0;
if (!(x & 0xffff0000u)) {
x <<= 16;
r -= 16;
}
if (!(x & 0xff000000u)) {
x <<= 8;
r -= 8;
}
if (!(x & 0xf0000000u)) {
x <<= 4;
r -= 4;
}
if (!(x & 0xc0000000u)) {
x <<= 2;
r -= 2;
}
if (!(x & 0x80000000u)) {
x <<= 1;
r -= 1;
}
return r;
}
void main()
{
int bit = 0;
int bit1 = 0;
int bit2 = 0;
int bit3 = 0;
int bit4 = 0;
int bit5 = 0;
bit = fls(1);
bit1 = fls(3);
bit2 = fls(7);
bit3 = fls(8);
bit4 = fls(0xf);
bit5 = fls(0x900);
printf("%d\n%d\n%d\n%d\n%d\n%d\n",bit,bit1,bit2,bit3,bit4,bit5);
}
執行結果:
1
2
3
4
4
12