-
Notifications
You must be signed in to change notification settings - Fork 2
/
bit_vector.h
96 lines (71 loc) · 1.42 KB
/
bit_vector.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
#ifndef __BIT_VECTOR_HH
#define __BIT_VECTOR_HH
#include <cstdint>
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class bit_vector
{
friend bool findCommonOne(bit_vector* a, bit_vector* b);
public:
bit_vector();
bit_vector(int64_t num_bits);
~bit_vector();
void set_one(int64_t);
void set_zero(int64_t);
void reset();
bool get(int64_t) const;
int64_t num_bits_set() const;
int64_t num_ones() const;
void print() const;
protected:
int64_t _num_bits;
uint64_t num_bytes;
void *_db;
};
inline
void bit_vector::reset()
{
memset(_db, 0, num_bytes);
}
inline
void bit_vector::print() const
{
cout << "_num_bits=" << _num_bits << endl;
for (int64_t i = _num_bits-1; i >= 0; i--) {
cout << get(i);
if (i % 8 == 0)
cout << " ";
}
cout << endl;
}
inline
int64_t bit_vector::num_bits_set() const
{
return _num_bits;
}
inline
int64_t bit_vector::num_ones() const
{
int64_t num = 0;
for (int64_t i = 0; i < _num_bits; i++)
if (get(i)) num++;
return num;
}
inline
void bit_vector::set_one(int64_t bit_idx)
{
static_cast<unsigned char*>(_db)[bit_idx >> 3] |= (1 << (bit_idx & 7));
}
inline
void bit_vector::set_zero(int64_t bit_idx)
{
static_cast<unsigned char*>(_db)[bit_idx >> 3] &= ~(1 << (bit_idx & 7));
}
inline
bool bit_vector::get(int64_t bit_idx) const
{
return (static_cast<unsigned char*>(_db)[bit_idx >> 3] >> (bit_idx & 7)) & 1;
}
#endif