This source file includes following definitions.
- bv_create
- bv_setbit
- bv_getbit
- bv_set
- bv_set2
- bv_set4
- bv_get
- bv_free
1 #include "bitvector.h"
2 #include "stdlib.h"
3 #include "stddef.h"
4
5 bit_vector_t* bv_create(int len, int nbits)
6 {
7 bit_vector_t* bm = (bit_vector_t*)malloc(sizeof(bit_vector_t));
8 if (bm == NULL)
9 return NULL;
10
11 bm->ptrLen = len * nbits / 8 + 1;
12 bm->nElem = len;
13 bm->nBits = nbits;
14 bm->ptr = malloc(bm->ptrLen);
15 if (bm->ptr == NULL)
16 {
17 free(bm);
18 return NULL;
19 }
20
21 return bm;
22 }
23
24
25 static inline void bv_setbit(const bit_vector_t* bm, int pos, int val)
26 {
27 int bp = pos - ((pos >> 3) << 3);
28 if (val == 0)
29 bm->ptr[pos >> 3] &= ~(1 << bp);
30 else
31 bm->ptr[pos >> 3] |= (1 << bp);
32 }
33
34
35 static inline int bv_getbit(const bit_vector_t* bm, int pos)
36 {
37
38
39
40
41
42 int bp = pos - ((pos >> 3) << 3);
43 return (bm->ptr[pos >> 3] & (1 << bp)) >> bp;
44 }
45
46 void bv_set(const bit_vector_t* bm, int pos, int val)
47 {
48 int i = bm->nBits - 1;
49 int bitpos = pos * bm->nBits;
50 do
51 {
52 bv_setbit(bm, bitpos + i, val & (1<<i));
53 }while(--i >= 0);
54 }
55
56
57
58 void bv_set2(const bit_vector_t* bm, int pos, int val)
59 {
60 int i;
61 int bitpos = pos * bm->nBits;
62 for (i = 0; i < bm->nBits; ++i)
63 {
64 int t = val & (1<<i);
65 bv_setbit(bm, bitpos + i, t);
66 bv_setbit(bm, bitpos + i + bm->nBits, t);
67 }
68 }
69
70
71
72 void bv_set4(const bit_vector_t* bm, int pos, int val)
73 {
74 int i;
75 int bitpos = pos * bm->nBits;
76 for (i = 0; i < bm->nBits; ++i)
77 {
78 int t = val & (1 << i);
79 bv_setbit(bm, bitpos + i, t);
80 bv_setbit(bm, bitpos + i + bm->nBits, t);
81 bv_setbit(bm, bitpos + i + bm->nBits * 2, t);
82 bv_setbit(bm, bitpos + i + bm->nBits * 3, t);
83 }
84 }
85
86 int bv_get(const bit_vector_t* bm, int pos)
87 {
88 int ret = 0;
89 int i = bm->nBits - 1;
90 int bitpos = pos * bm->nBits;
91 do
92 {
93 ret |= (bv_getbit(bm, bitpos + i) << i);
94 }while(--i >= 0);
95
96 return ret;
97 }
98
99
100 void bv_free(bit_vector_t* bm)
101 {
102 if (bm)
103 {
104 if (bm->ptr)
105 {
106 free(bm->ptr);
107 bm->ptr = NULL;
108 }
109
110 free(bm);
111 }
112 }
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148