-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitarr.cpp
148 lines (131 loc) · 2.37 KB
/
bitarr.cpp
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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
/*
* bits.cpp
*
* Created on: 19.12.2014
* Author: roman
*/
#include "bitarr.h"
#include <iostream>
bool bitarr::operator==(const bitarr& bitarr2)
{
if (size() != bitarr2.size())
return false;
for (int i=0; i<array.size(); i++)
if (array[i] != bitarr2.array[i])
return false;
return true;
}
bitarr::operator uint64_t() const
{
if (size() > 64)
return 0;
uint64_t v = 0;
for (int i=0; i<size(); i++) {
v <<= 1;
if (get(i))
v |= 1;
}
return v;
}
string bitarr::print() const
{
string str = "{";
for (int i=0; i<size(); i++)
str += std::to_string(get(i));
str += "}";
return str;
}
std::ostream& operator<<(std::ostream& os, const bitarr &b)
{
return os << b.print();
}
void bitarr::append(bool b)
{
uint64_t c;
if (array.size() == 0)
c = 0;
else
c = array[array.size() - 1];
if (cur_pos < 64) {
c |= ((uint64_t)b) << cur_pos;
cur_pos++;
array[array.size() - 1] = c;
} else {
c = b;
array.push_back(c);
cur_pos = 1;
}
}
void bitarr::append(uint64_t v, int n)
{
for (int i=n-1; i>=0; i--)
append(v & (1ULL << i));
}
void bitarr::append(bitarr bar)
{
for (int i=0; i<bar.size(); i++)
append(bar.get(i));
}
void bitarr::set(size_t pos, bool value)
{
size_t p = pos / 64;
if (p > array.size())
return;
pos -= p * 64;
array[p] &= ~(1<<pos);
array[p] |= value << pos;
}
bool bitarr::get(size_t pos) const
{
size_t p = pos / 64;
if (p > array.size())
return false;
pos -= p * 64;
return (array[p] & (1 << pos)) >> pos;
}
void bitarr::cut(size_t pos)
{
if (pos > size())
return;
bitarr tmp;
for (int i=0; i<pos; i++)
tmp.append(get(i));
for (int i=pos+1; i<size(); i++)
tmp.append(get(i));
array = tmp.array;
cur_pos = tmp.cur_pos;
}
int bitarr::write(FILE *f)
{
int offset = 0;
if (fseek(f, offset, SEEK_SET))
return -1;
fwrite(&cur_pos, sizeof(uint64_t), 1, f);
for (int i=0; i<array.size();i++) {
uint64_t v = array[i];
if (fwrite(&v, 1, sizeof(uint64_t), f) != sizeof(uint64_t))
return -1;
}
return 0;
}
int bitarr::read(FILE *f)
{
int offset = 0;
if (fseek(f, offset, SEEK_SET))
return -1;
fread(&cur_pos, sizeof(uint64_t), 1, f);
unsigned char v;
while (fread(&v, sizeof(uint64_t), 1, f) == 1)
array.push_back(v);
return 0;
}
void bitarr::clear()
{
array.clear();
cur_pos = 64;
}
bitarr::bitarr() {
cur_pos = 64;
}
bitarr::~bitarr() {
}