libcstl
Loading...
Searching...
No Matches
common.c
Go to the documentation of this file.
1/*!
2 * @file
3 */
4
5#include "cstl/common.h"
6
7int cstl_fls(const unsigned long x)
8{
9 int i = -1;
10
11 if (x != 0) {
12 unsigned int b;
13
14 /*
15 * this loop performs a binary search by setting
16 * the upper half of the bits and determining if
17 * a bit in the input is set in that half.
18 *
19 * each iteration of the loop reduces the size of
20 * the mask by half and either moves it to the upper
21 * half of the previous half (if a set bit was found)
22 * or the upper half of the previous unset half (if
23 * a set bit was not found).
24 *
25 * the runtime of the algorithm is log2(n) where n
26 * is the total number of bits in the input value.
27 */
28
29 for (i = 0, b = (8 * sizeof(x)) / 2; b != 0; b /= 2) {
30 const unsigned int s = b + i;
31 unsigned long m;
32
33 m = ~0;
34 m <<= s;
35
36 if ((x & m) != 0) {
37 i = s;
38 }
39 }
40 }
41
42 return i;
43}
44
45#ifdef __cfg_test__
46// GCOV_EXCL_START
47#include <check.h>
48#include <stdlib.h>
49
50START_TEST(fls)
51{
52 ck_assert_int_eq(cstl_fls(0), -1);
53 ck_assert_int_eq(cstl_fls(1), 0);
54 ck_assert_int_eq(cstl_fls(3), 1);
55 ck_assert_int_eq(cstl_fls(3 << 16), 17);
56 ck_assert_int_eq(cstl_fls(~0UL), 8 * sizeof(unsigned long) - 1);
57 ck_assert_int_eq(cstl_fls(0x5a5a5a5a), 30);
58}
59END_TEST
60
61START_TEST(swap)
62{
63#define SWAP_TEST(TYPE) \
64 do { \
65 TYPE x = rand(), y = rand(), t; \
66 const TYPE a = x, b = y; \
67 cstl_swap(&x, &y, &t, sizeof(t)); \
68 ck_assert_mem_eq(&a, &y, sizeof(a)); \
69 ck_assert_mem_eq(&b, &x, sizeof(a)); \
70 } while (0)
71
72 SWAP_TEST(uint8_t);
73 SWAP_TEST(uint16_t);
74 SWAP_TEST(uint32_t);
75 SWAP_TEST(uint64_t);
76
77#undef SWAP_TEST
78}
79
80Suite * common_suite(void)
81{
82 Suite * const s = suite_create("common");
83
84 TCase * tc;
85
86 tc = tcase_create("common");
87 tcase_add_test(tc, fls);
88 tcase_add_test(tc, swap);
89 suite_add_tcase(s, tc);
90
91 return s;
92}
93
94// GCOV_EXCL_STOP
95#endif
int cstl_fls(const unsigned long x)
Find the last (highest order) bit set.
Definition common.c:7