-
Notifications
You must be signed in to change notification settings - Fork 0
/
v2_decoder.cpp
124 lines (114 loc) · 2.71 KB
/
v2_decoder.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
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <fstream>
using namespace std;
struct Node {
char c;
Node *left, *right;
int id;
Node() {
left = nullptr;
right = nullptr;
}
Node(char c, int id) {
this->c = c;
this->id = id;
left = nullptr;
right = nullptr;
}
bool isTerm() {
return left == nullptr && right == nullptr;
}
};
Node *root = nullptr;
map<char, string> table;
void dfs(Node *now, string &s) {
if (now == nullptr)
return;
if (now->isTerm()) {
table[now->c] = s;
}
s += '0';
dfs(now->left, s);
s.pop_back();
s += '1';
dfs(now->right, s);
s.pop_back();
}
void print(int &ind, string &s, Node *p) {
if (p->isTerm()) {
cout << p->c;
if (p == root) {
ind++;
}
return;
}
if (s[ind] == '0')
print(++ind, s, p->left);
else
print(++ind, s, p->right);
}
Node * loadTree() {
std::ifstream in("/Users/andrewmoskalev/CLionProjects/Haffman/cmake-build-debug/generator.output");
string s_n = "";
char * tmp = new char;
char * c = new char;
while (in.read(tmp, 1)) {
if (*tmp == '\n')
break;
s_n += *tmp;
}
int n = stoi(s_n);
std::vector<pair<Node *, int>> v(n);
for (int i = 0; i < n; ++i) {
in.read(c, 1);
string pInd = "";
while (in.read(tmp, 1)) {
if (*tmp == '\n') {
break;
}
pInd += *tmp;
}
int p = stoi(pInd);
v[i] = {new Node(*c, i), p};
}
for (int i = 1; i < n; ++i) {
if (v[v[i].second].first->left == nullptr) {
v[v[i].second].first->left = v[i].first;
} else {
v[v[i].second].first->right = v[i].first;
}
}
return v[0].first;
}
int main() {
char *buf = new char;
root = loadTree();
ifstream inp("encoder.output");
uint64_t encodeSize = 0;
for (int i = 0; i < 8; ++i) {
encodeSize <<= 8;
inp.read(buf, 1);
encodeSize |= (unsigned char) (*buf);
}
string s;
for (uint64_t i = 0; i < encodeSize; i += 8) {
if ((i + 8 > encodeSize) && (encodeSize % 8 != 0)) {
inp.read(buf, 1);
encodeSize %= 8;
for (int j = 0; j < encodeSize; ++j)
s += (((*buf & (1 << (7 - j))) >> (7 - j)) + '0');
break;
}
inp.read(buf, 1);
for (int j = 0; j < 8; ++j)
s += ((*buf & (1 << (7 - j))) >> (7 - j)) + '0';
}
freopen("decoder.output", "w", stdout);
int ind = 0;
while (ind < s.size())
print(ind, s, root);
return 0;
}