-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbit_stack.h
More file actions
70 lines (51 loc) · 1.12 KB
/
bit_stack.h
File metadata and controls
70 lines (51 loc) · 1.12 KB
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
#ifndef __BIT_STACK_H__
#define __BIT_STACK_H__
#include <vector>
class BitStack {
private:
std::vector<unsigned> vec;
int bitCount, bitOffset;
public:
BitStack() : bitCount(0), bitOffset(0) {
vec.push_back(0);
}
void push(int bit) {
if (bitOffset == 32) {
vec.push_back(0);
bitOffset = 0;
}
unsigned onebit = 1 << bitOffset;
// set or unset the given bit
if (bit) {
vec[vec.size()-1] |= onebit;
} else {
vec[vec.size()-1] &= ~onebit;
}
bitOffset++;
}
int pop() {
if (bitOffset == 0) {
if (vec.empty()) return 0;
bitOffset = 32;
vec.pop_back();
}
bitOffset--;
unsigned mask = 1u << bitOffset;
int bit = vec[vec.size()-1] & mask;
// clear the bit
vec[vec.size()-1] &= ~mask;
// make sure it's just 1 or 0
return bit != 0;
}
// include partial words
int getWordCount() const {
return (int) vec.size();
}
int getBitCount() const {
return ((int)vec.size() - 1) * 32 + bitOffset;
}
unsigned getWord(int i) const {
return vec[i];
}
};
#endif // __BIT_STACK_H__