Tenok
A Linux-like Real-Time Operating System for Robotics and Internet of Things
log2.h
Go to the documentation of this file.
1 
4 #ifndef __LOG2_H__
5 #define __LOG2_H__
6 
7 #include <common/bitops.h>
8 
9 /* clang-format off */
10 #define ilog2(x) \
11 ( \
12  __builtin_constant_p(x) ? ( \
13  (x) < 1 ? __ilog2_NaN() : \
14  (x) & (1ul << 31) ? 31 : \
15  (x) & (1ul << 30) ? 30 : \
16  (x) & (1ul << 29) ? 29 : \
17  (x) & (1ul << 28) ? 28 : \
18  (x) & (1ul << 27) ? 27 : \
19  (x) & (1ul << 26) ? 26 : \
20  (x) & (1ul << 25) ? 25 : \
21  (x) & (1ul << 24) ? 24 : \
22  (x) & (1ul << 23) ? 23 : \
23  (x) & (1ul << 22) ? 22 : \
24  (x) & (1ul << 21) ? 21 : \
25  (x) & (1ul << 20) ? 20 : \
26  (x) & (1ul << 19) ? 19 : \
27  (x) & (1ul << 18) ? 18 : \
28  (x) & (1ul << 17) ? 17 : \
29  (x) & (1ul << 16) ? 16 : \
30  (x) & (1ul << 15) ? 15 : \
31  (x) & (1ul << 14) ? 14 : \
32  (x) & (1ul << 13) ? 13 : \
33  (x) & (1ul << 12) ? 12 : \
34  (x) & (1ul << 11) ? 11 : \
35  (x) & (1ul << 10) ? 10 : \
36  (x) & (1ul << 9) ? 9 : \
37  (x) & (1ul << 8) ? 8 : \
38  (x) & (1ul << 7) ? 7 : \
39  (x) & (1ul << 6) ? 6 : \
40  (x) & (1ul << 5) ? 5 : \
41  (x) & (1ul << 4) ? 4 : \
42  (x) & (1ul << 3) ? 3 : \
43  (x) & (1ul << 2) ? 2 : \
44  (x) & (1ul << 1) ? 1 : \
45  (x) & (1ul << 0) ? 0 : \
46  __ilog2_NaN() \
47  ) : \
48  __ilog2(x) \
49 )
50 /* clang-format on */
51 
52 static inline unsigned long __ilog2(unsigned long x)
53 {
54  return _flsl(x) - 1;
55 }
56 
57 static inline /*__atrribute__(noreturn)*/ unsigned long __ilog2_NaN(void)
58 {
59  while (1)
60  ;
61  return 0;
62 }
63 
64 #endif