1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 #ifndef _BITSTRING_H_
38 #define _BITSTRING_H_
39
40 typedef unsigned char bitstr_t;
41
42
43
44 #define _bit_byte(bit) \
45 ((bit) >> 3)
46
47
48 #define _bit_mask(bit) \
49 (1 << ((bit)&0x7))
50
51
52
53 #define bitstr_size(nbits) \
54 ((((nbits) - 1) >> 3) + 1)
55
56
57 #define bit_alloc(nbits) \
58 (bitstr_t *)calloc(1, \
59 (unsigned int)bitstr_size(nbits) * sizeof(bitstr_t))
60
61
62 #define bit_decl(name, nbits) \
63 (name)[bitstr_size(nbits)]
64
65
66 #define bit_test(name, bit) \
67 ((name)[_bit_byte(bit)] & _bit_mask(bit))
68
69
70 #define bit_set(name, bit) \
71 (name)[_bit_byte(bit)] |= (bitstr_t)_bit_mask(bit)
72
73
74 #define bit_clear(name, bit) \
75 (name)[_bit_byte(bit)] &= (bitstr_t)~_bit_mask(bit)
76
77
78 #define bit_nclear(name, start, stop) { \
79 register bitstr_t *_name = name; \
80 register int _start = start, _stop = stop; \
81 register int _startbyte = _bit_byte(_start); \
82 register int _stopbyte = _bit_byte(_stop); \
83 if (_startbyte == _stopbyte) { \
84 _name[_startbyte] &= (bitstr_t)((0xff >> (8 - (_start&0x7))) | \
85 (0xff << ((_stop&0x7) + 1))); \
86 } else { \
87 _name[_startbyte] &= (bitstr_t)(0xff >> (8 - (_start&0x7))); \
88 while (++_startbyte < _stopbyte) \
89 _name[_startbyte] = 0; \
90 _name[_stopbyte] &= (bitstr_t)(0xff << ((_stop&0x7) + 1)); \
91 } \
92 }
93
94
95 #define bit_nset(name, start, stop) { \
96 register bitstr_t *_name = name; \
97 register int _start = start, _stop = stop; \
98 register int _startbyte = _bit_byte(_start); \
99 register int _stopbyte = _bit_byte(_stop); \
100 if (_startbyte == _stopbyte) { \
101 _name[_startbyte] |= (bitstr_t)((0xff << (_start&0x7)) & \
102 (0xff >> (7 - (_stop&0x7)))); \
103 } else { \
104 _name[_startbyte] |= (bitstr_t)(0xff << ((_start)&0x7)); \
105 while (++_startbyte < _stopbyte) \
106 _name[_startbyte] = 0xff; \
107 _name[_stopbyte] |= (bitstr_t)(0xff >> (7 - (_stop&0x7))); \
108 } \
109 }
110
111
112 #define bit_ffc(name, nbits, value) { \
113 register bitstr_t *_name = name; \
114 register int _byte, _nbits = nbits; \
115 register int _stopbyte = _bit_byte(_nbits), _value = -1; \
116 for (_byte = 0; _byte <= _stopbyte; ++_byte) \
117 if (_name[_byte] != 0xff) { \
118 _value = _byte << 3; \
119 for (_stopbyte = _name[_byte]; (_stopbyte&0x1); \
120 ++_value, _stopbyte >>= 1); \
121 break; \
122 } \
123 *(value) = _value; \
124 }
125
126
127 #define bit_ffs(name, nbits, value) { \
128 register bitstr_t *_name = name; \
129 register int _byte, _nbits = nbits; \
130 register int _stopbyte = _bit_byte(_nbits), _value = -1; \
131 for (_byte = 0; _byte <= _stopbyte; ++_byte) \
132 if (_name[_byte]) { \
133 _value = _byte << 3; \
134 for (_stopbyte = _name[_byte]; !(_stopbyte&0x1); \
135 ++_value, _stopbyte >>= 1); \
136 break; \
137 } \
138 *(value) = _value; \
139 }
140
141 #endif