]> git.ozlabs.org Git - ccan/blob - ccan/bitops/bitops.c
crypto/shachain/tools: update to new rbuf API.
[ccan] / ccan / bitops / bitops.c
1 /* CC0 license (public domain) - see LICENSE file for details */
2 #include <ccan/bitops/bitops.h>
3 #include <stdlib.h>
4
5 /* We do naive replacement versions: good for testing, and really your
6  * compiler should do better. */
7 #ifdef BITOPS_NEED_FFS
8 int bitops_ffs32(uint32_t u)
9 {
10         int i;
11         for (i = 0; i < 32; i++)
12                 if (u & ((uint32_t)1 << i))
13                         return i + 1;
14         return 0;
15 }
16
17 int bitops_ffs64(uint64_t u)
18 {
19         int i;
20         for (i = 0; i < 64; i++)
21                 if (u & ((uint64_t)1 << i))
22                         return i + 1;
23         return 0;
24 }
25 #endif
26
27 #ifdef BITOPS_NEED_CLZ
28 int bitops_clz32(uint32_t u)
29 {
30         int i;
31         for (i = 0; i < 32; i++)
32                 if (u & ((uint32_t)1 << (31 - i)))
33                         return i;
34         abort();
35 }
36
37 int bitops_clz64(uint64_t u)
38 {
39         int i;
40         for (i = 0; i < 64; i++)
41                 if (u & ((uint64_t)1 << (63 - i)))
42                         return i;
43         abort();
44 }
45 #endif
46
47 #ifdef BITOPS_NEED_CTZ
48 int bitops_ctz32(uint32_t u)
49 {
50         BITOPS_ASSERT_NONZERO(u);
51         return bitops_ffs32(u) - 1;
52 }
53
54 int bitops_ctz64(uint64_t u)
55 {
56         BITOPS_ASSERT_NONZERO(u);
57         return bitops_ffs64(u) - 1;
58 }
59 #endif
60
61 #ifdef BITOPS_NEED_WEIGHT
62 int bitops_weight32(uint32_t u)
63 {
64         int i, num = 0;
65         for (i = 0; i < 32; i++)
66                 if (u & ((uint32_t)1 << i))
67                         num++;
68         return num;
69 }
70
71 int bitops_weight64(uint64_t u)
72 {
73         int i, num = 0;
74         for (i = 0; i < 64; i++)
75                 if (u & ((uint64_t)1 << i))
76                         num++;
77         return num;
78 }
79 #endif