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
| #include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const int wordSize = 1; // in bytes
const int offset = 128;
bool getBit(const unsigned char *a, int no) {
no = (wordSize * 8) - no - 1;
return ((1 << no) & (*a)) != 0;
}
void putBit(unsigned char *a, int no, bool value) {
no = (wordSize * 8) - no - 1;
if (value) *a |= 1 << no;
else *a &= ~(1 << no);
}
void write(unsigned char *a, int p, int n) {
for (int i = 0; i <= n; i++) {
int wordNo = (p + i) / (wordSize * 8);
int bitNo = (p + i) % (wordSize * 8);
putBit(a + wordNo, bitNo, i != n);
}
}
bool compare(pair<int, char> a, pair<int, char> b) {
return a.first > b.first;
}
int *getAssoc(const char *str, int size) {
int counts[256];
for (int i = 0; i < 256; i++) {
counts[i] = 0;
}
for (int i = 0; i < size; i++) {
counts[str[i] + offset]++;
}
pair<int, char> rel[256];
for (int i = 0; i < 256; i++) {
rel[i] = make_pair(counts[i], (char) (i - offset));
}
sort(rel, rel + 256, compare);
int *assoc = new int[256];
for (int i = 0; i < 256; i++) {
assoc[rel[i].second + offset] = i;
}
return assoc;
}
int main() {
const char *str = "Alan real pussy";
int size = 0;
while (str[size] != '\0') size++;
int *assoc = getAssoc(str, size);
int encodedBits = 0;
for (int i = 0; i < size; i++) {
encodedBits += assoc[str[i] + offset] + 1;
}
int encodedWords = encodedBits / (8 * wordSize);
unsigned char *result = new unsigned char[encodedWords];
for (int i = 0; i < encodedWords; i++) {
result[i] = 0;
}
int position = 0;
for (int i = 0; i < size; i++) {
write(result, position, assoc[str[i] + offset]);
position += assoc[str[i] + offset] + 1;
}
float k = (float) size * 8 * wordSize / encodedBits;
cout << "Koefficient sjatia: " << k << endl;
for (int i = 0; i < encodedBits; i++) {
cout << getBit(result + i / (8 * wordSize), i % (8 * wordSize));
}
return 0;
} |