-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.cpp
88 lines (80 loc) · 1.83 KB
/
reader.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
#include "reader.h"
Reader::Reader(const std::string &filename) {
in_.open(filename, std::ios::binary);
buffer_ = 0;
last_index_ = 8;
}
Reader::~Reader() {
in_.close();
}
void Reader::Open(const std::string &filename) {
in_.close();
in_.open(filename, std::ios::binary);
buffer_ = 0;
last_index_ = 8;
}
std::vector<bool> Reader::ReadBits(size_t cnt) {
std::vector<bool> answer;
while (cnt > 0 && !in_.eof()) {
if (last_index_ == 8) {
last_index_ = 0;
char c;
in_.read(&c, 1);
if (in_.eof()) {
break;
}
buffer_ = static_cast<unsigned char>(c);
}
--cnt;
answer.push_back(buffer_ & 1);
buffer_ >>= 1;
++last_index_;
}
while (cnt > 0) {
answer.push_back(false);
--cnt;
}
return answer;
}
std::vector<bool> Reader::ReadBitsToEnd(size_t cnt) {
std::vector<bool> answer;
while (cnt > 0 && !in_.eof()) {
if (last_index_ == 8) {
last_index_ = 0;
char c;
in_.read(&c, 1);
if (in_.eof()) {
break;
}
buffer_ = static_cast<unsigned char>(c);
}
--cnt;
answer.push_back(buffer_ & 1);
buffer_ >>= 1;
++last_index_;
}
return answer;
}
unsigned char Reader::ReadChar() {
std::vector<bool> answer = ReadBits(8);
unsigned char c = 0;
for (int i = 0; i < 8; ++i) {
if (answer[i]) {
c += 1 << i;
}
}
return c;
}
size_t Reader::ReadBytesToInt(size_t cnt) {
std::vector <bool> answer = ReadBits(cnt);
size_t n = 0;
for (int i = 0; i < cnt; ++i) {
if (answer[i]) {
n += 1 << i;
}
}
return n;
}
bool Reader::Eof() {
return in_.eof();
}