使用与、或、移位来实现位向量操作
实现思路摘自Programming Pearls,比较简单不再做解释了
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 #include <assert.h>
2 #include <stdio.h>
3 #include <strings.h>
4
5 #define BITSPERWORD (32)
6 #define SHIFT (5)
7 #define MASK (0x1F)
8 #define MAX_LEN (35)
9
10 void
11 init(int *vec, int len)
12 {
13 assert(NULL != vec && len >= 0);
14 bzero(vec, sizeof(int)*len);
15 return;
16 }
17
18 void
19 set(int *vec, int index)
20 {
21 assert(vec != NULL);
22 assert(index >= 0 && index <= MAX_LEN);
23 vec[index >> SHIFT] |= (1 << (index & MASK) );
24 return;
25 }
26
27 void
28 clr(int *vec, int index)
29 {
30 assert(vec != NULL);
31 assert(index >= 0 && index <= MAX_LEN);
32 vec[index >> SHIFT] &= ~(1 << (index & MASK) );
33 return;
34 }
35
36 int test(int *vec, int index)
37 {
38 assert(vec != NULL);
39 assert(index >= 0 && index <= MAX_LEN);
40 return ( vec[index >> SHIFT] & (1 << ( index & MASK)) );
41 }
42
43 int main(void)
44 {
45 // 注意在定义向量长度时要多加一个1
46 int vec[1 + MAX_LEN/BITSPERWORD];
47
48 init(vec, 1+MAX_LEN/BITSPERWORD);
49 set(vec, 35);
50 if ( test(vec, 35) )
51 {
52 printf("set test pass\n");
53 }
54
55 //
56 clr(vec, 35);
57 if ( !test(vec, 35) )
58 {
59 printf("clr test pass\n");
60 }
61
62 return 0;
63 }