Tenok
A Linux-like Real-Time Operating System for Robotics and Internet of Things
bitops.h
Go to the documentation of this file.
1 
4 #ifndef __BITOPS_H__
5 #define __BITOPS_H__
6 
7 #include <sys/param.h>
8 
9 #define BITS_PER_CHAR 8
10 #define BITS_PER_LONG (BITS_PER_CHAR * sizeof(long))
11 
12 /* Find last bit set:
13  * the index of the last bit that's set, or 0 if value is zero.
14  */
15 static inline unsigned long _flsl(unsigned long word)
16 {
17  return word ? sizeof(long) * BITS_PER_CHAR - __builtin_clz(word) : 0;
18 }
19 
20 static inline void clear_bit(unsigned long bit, unsigned long *word)
21 {
22  *word &= ~(1 << bit);
23 }
24 
25 static inline void set_bit(unsigned long bit, unsigned long *word)
26 {
27  *word |= (1 << bit);
28 }
29 
30 static inline void bitmap_clear_bit(unsigned long *map, unsigned long bit)
31 {
32  clear_bit(bit % BITS_PER_LONG, &map[bit / BITS_PER_LONG]);
33 }
34 
35 static inline void bitmap_set_bit(unsigned long *map, unsigned long bit)
36 {
37  set_bit(bit % BITS_PER_LONG, &map[bit / BITS_PER_LONG]);
38 }
39 
40 static inline unsigned long bitmap_get_bit(unsigned long *map,
41  unsigned long bit)
42 {
43  return map[bit / BITS_PER_LONG] >> (bit % BITS_PER_LONG) & 1;
44 }
45 
46 static inline unsigned long find_first_bit(const unsigned long *addr,
47  unsigned long size)
48 {
49  for (unsigned long i = 0; i * BITS_PER_LONG < size; i++) {
50  if (addr[i]) {
51  return MIN(i * BITS_PER_LONG + __builtin_ffsl(addr[i]) - 1, size);
52  }
53  }
54 
55  return size;
56 }
57 
58 static inline unsigned long find_first_zero_bit(const unsigned long *addr,
59  unsigned long size)
60 {
61  for (unsigned long i = 0; i * BITS_PER_LONG < size; i++) {
62  if (addr[i] != ~0ul) {
63  return MIN(i * BITS_PER_LONG + __builtin_ffsl(~addr[i]) - 1, size);
64  }
65  }
66 
67  return size;
68 }
69 
70 #endif