-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
bitset.h
96 lines (79 loc) · 1.73 KB
/
bitset.h
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*******************************************************************************
* DANIEL'S ALGORITHM IMPLEMENTAIONS
*
* /\ | _ _ ._ o _|_ |_ ._ _ _
* /--\ | (_| (_) | | |_ | | | | | _>
* _|
*
* BIT-SET
*
* a bit-set data structure
*
******************************************************************************/
#ifndef ALGO_BIT_SET_H__
#define ALGO_BIT_SET_H__
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
namespace alg {
/**
* definition of bitset class
*/
class BitSet {
private:
uint32_t m_size; //size in bits
uint32_t m_bytes; // size in bytes
unsigned char * m_bits; // the bits
public:
/**
* construct BitSet by a give number of bits
*/
BitSet(uint32_t num_bits) {
// round up
m_bytes = num_bits/8+1;
m_size = m_bytes * 8;
m_bits = new unsigned char[m_bytes];
memset(m_bits, 0, m_bytes);
}
/**
* safely free
*/
~BitSet() {
delete [] m_bits;
}
private:
BitSet(const BitSet&);
BitSet& operator=(const BitSet&);
public:
/**
* set 1 to position [bit]
*/
inline void set(uint32_t bit) {
if (bit>=m_size) return;
uint32_t n = bit/8;
uint32_t off = bit%8;
m_bits[n] |= 128U>>off;
}
/**
* set 0 to position [bit]
*/
inline void unset(uint32_t bit) {
if (bit>=m_size) return;
uint32_t n = bit/8;
uint32_t off = bit%8;
m_bits[n] &= ~(128U>>off);
}
/**
* test a bit , true if set, false if not.
*/
inline bool test(uint32_t bit) {
if (bit>=m_size) return false;
uint32_t n = bit/8;
uint32_t off = bit%8;
if (m_bits[n] & (128U>>off))return true;
return false;
}
};
}
#endif //