]> mj.ucw.cz Git - libucw.git/blob - ucw/bit-fls.c
tableprinter: code cleanup
[libucw.git] / ucw / bit-fls.c
1 /*
2  *      UCW Library -- Find Highest Set Bit
3  *
4  *      (c) 1997-2005 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include <ucw/lib.h>
11 #include <ucw/bitops.h>
12
13 int
14 bit_fls(u32 x)
15 {
16   uint l;
17
18   if (!x)
19         return -1;
20
21   l = 0;
22   if (x & 0xffff0000) { l += 16; x &= 0xffff0000; }
23   if (x & 0xff00ff00) { l += 8;  x &= 0xff00ff00; }
24   if (x & 0xf0f0f0f0) { l += 4;  x &= 0xf0f0f0f0; }
25   if (x & 0xcccccccc) { l += 2;  x &= 0xcccccccc; }
26   if (x & 0xaaaaaaaa) l++;
27   return l;
28 }
29
30 #ifdef TEST
31
32 #include <stdio.h>
33
34 int main(void)
35 {
36   uint i;
37   while (scanf("%x", &i) == 1)
38     printf("%d\n", bit_fls(i));
39   return 0;
40 }
41
42 #endif