-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHuffmanDataCompression.cpp
More file actions
212 lines (181 loc) · 6.24 KB
/
HuffmanDataCompression.cpp
File metadata and controls
212 lines (181 loc) · 6.24 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
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#include <iostream>
#include <fstream>
#include <queue>
#include <unordered_map>
#include <vector>
#include <bitset>
#include <cstdint>
using namespace std;
struct Node {
char ch;
int freq;
Node* left;
Node* right;
Node(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {}
};
struct Compare {
bool operator()(Node* a, Node* b) {
return a->freq > b->freq;
}
};
void buildCodes(Node* root, const string& code, unordered_map<char, string>& codes) {
if (!root) return;
if (!root->left && !root->right) codes[root->ch] = code;
buildCodes(root->left, code + "0", codes);
buildCodes(root->right, code + "1", codes);
}
void freeTree(Node* root) {
if (!root) return;
freeTree(root->left);
freeTree(root->right);
delete root;
}
Node* rebuildTree(const unordered_map<char, string>& codes) {
Node* root = new Node('\0', 0);
for (auto& [ch, code] : codes) {
Node* cur = root;
for (char bit : code) {
if (bit == '0') {
if (!cur->left) cur->left = new Node('\0', 0);
cur = cur->left;
} else {
if (!cur->right) cur->right = new Node('\0', 0);
cur = cur->right;
}
}
cur->ch = ch;
}
return root;
}
string bytesToBits(const vector<uint8_t>& data, size_t validBits) {
string bits;
for (uint8_t b : data) bits += bitset<8>(b).to_string();
return bits.substr(0, validBits);
}
vector<uint8_t> bitsToBytes(const string& bits) {
vector<uint8_t> result;
for (size_t i = 0; i < bits.length(); i += 8) {
string byteStr = bits.substr(i, 8);
while (byteStr.size() < 8) byteStr += '0';
result.push_back(static_cast<uint8_t>(bitset<8>(byteStr).to_ulong()));
}
return result;
}
void compressFile(const string& inputPath, const string& outputPath) {
ifstream in(inputPath, ios::binary);
if (!in) {
cout << "Ошибка открытия файла\n";
return;
}
string data((istreambuf_iterator<char>(in)), istreambuf_iterator<char>());
in.close();
unordered_map<char, int> freq;
for (char c : data) freq[c]++;
priority_queue<Node*, vector<Node*>, Compare> pq;
for (auto& [ch, f] : freq) pq.push(new Node(ch, f));
while (pq.size() > 1) {
Node* l = pq.top(); pq.pop();
Node* r = pq.top(); pq.pop();
Node* merged = new Node('\0', l->freq + r->freq);
merged->left = l;
merged->right = r;
pq.push(merged);
}
Node* root = pq.top();
unordered_map<char, string> codes;
buildCodes(root, "", codes);
string bits;
for (char c : data) bits += codes[c];
size_t validBits = bits.length();
vector<uint8_t> byteData = bitsToBytes(bits);
ofstream out(outputPath, ios::binary);
size_t codeCount = codes.size();
out.write(reinterpret_cast<char*>(&codeCount), sizeof(size_t));
for (auto& [ch, code] : codes) {
out.write(&ch, 1);
size_t len = code.length();
out.write(reinterpret_cast<char*>(&len), sizeof(size_t));
out.write(code.c_str(), len);
}
out.write(reinterpret_cast<char*>(&validBits), sizeof(size_t));
size_t dataSize = byteData.size();
out.write(reinterpret_cast<char*>(&dataSize), sizeof(size_t));
out.write(reinterpret_cast<char*>(byteData.data()), dataSize);
out.close();
freeTree(root);
cout << "Сжатие завершено. Сохранено в " << outputPath << "\n";
}
void decompressFile(const string& inputPath, const string& outputPath) {
ifstream in(inputPath, ios::binary);
if (!in) {
cout << "Ошибка открытия файла\n";
return;
}
size_t codeCount;
in.read(reinterpret_cast<char*>(&codeCount), sizeof(size_t));
unordered_map<char, string> codes;
for (size_t i = 0; i < codeCount; ++i) {
char ch;
size_t len;
in.read(&ch, 1);
in.read(reinterpret_cast<char*>(&len), sizeof(size_t));
string code(len, ' ');
in.read(code.data(), len);
codes[ch] = code;
}
size_t validBits, dataSize;
in.read(reinterpret_cast<char*>(&validBits), sizeof(size_t));
in.read(reinterpret_cast<char*>(&dataSize), sizeof(size_t));
vector<uint8_t> byteData(dataSize);
in.read(reinterpret_cast<char*>(byteData.data()), dataSize);
in.close();
Node* root = rebuildTree(codes);
string bits = bytesToBits(byteData, validBits);
string result;
Node* cur = root;
for (char bit : bits) {
cur = (bit == '0') ? cur->left : cur->right;
if (!cur->left && !cur->right) {
result += cur->ch;
cur = root;
}
}
ofstream out(outputPath, ios::binary);
out.write(result.data(), result.size());
out.close();
// Оценка степени сжатия
ifstream inOrig(inputPath, ios::binary | ios::ate);
ifstream inComp(outputPath, ios::binary | ios::ate);
auto origSize = inOrig.tellg();
auto compSize = inComp.tellg();
inOrig.close();
inComp.close();
double ratio = (1.0 - (double)compSize / (double)origSize) * 100.0;
cout << "Сжатие завершено. Сохранено в " << outputPath << "\n";
cout << "Исходный размер: " << origSize << " байт\n";
cout << "Сжатый размер: " << compSize << " байт\n";
cout << "Степень сжатия: " << ratio << " %\n";
}
int main() {
cout << "1 — Сжать файл\n2 — Распаковать файл\nВыбор: ";
int choice;
cin >> choice;
cin.ignore();
string inFile, outFile;
if (choice == 1) {
cout << "Введите имя файла для сжатия: ";
getline(cin, inFile);
cout << "Введите имя выходного файла (например, файл.huff): ";
getline(cin, outFile);
compressFile(inFile, outFile);
} else if (choice == 2) {
cout << "Введите имя сжатого файла: ";
getline(cin, inFile);
cout << "Введите имя выходного файла: ";
getline(cin, outFile);
decompressFile(inFile, outFile);
} else {
cout << "Неверный выбор\n";
}
return 0;
}