-
Notifications
You must be signed in to change notification settings - Fork 0
/
base64.cc
120 lines (112 loc) · 2.81 KB
/
base64.cc
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
#include <fstream>
#include <iostream>
#define rep(i, a, b) for(int i = (a); i < int(b); ++i)
#define trav(it, v) for(typeof((v).begin()) it = (v).begin(); \
it != (v).end(); ++it)
using namespace std;
char const base64[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
void compress(fstream &infile, ostream &outfile){
int j = 0;
while(1){
int n = 0, filled_bytes_at_eof = 3, c;
rep(i, 0, 3){
c = infile.get();
if(c == EOF){
filled_bytes_at_eof = i;
break;
}
else{
n = n << 8;
n += c;
}
}
switch(filled_bytes_at_eof){
case 3:
outfile.put(base64[(n>>18) & 0x3f]);
outfile.put(base64[(n>>12) & 0x3f]);
outfile.put(base64[(n>>6) & 0x3f]);
outfile.put(base64[n & 0x3f]);
break;
case 2:
outfile.put(base64[(n>>12) & 0x3f]);
outfile.put(base64[(n>>6) & 0x3f]);
outfile.put(base64[n & 0x3f]);
outfile.put('=');
break;
case 1:
outfile.put(base64[(n>>6) & 0x3f]);
outfile.put(base64[n & 0x3f]);
outfile.put('=');
outfile.put('=');
break;
}
if(++j%19 == 0) outfile.put('\n');
if(c == EOF) break;
}
outfile.put('\n');
}
void decompress(fstream &infile, ostream &outfile){
int decode[256];
rep(i, 0, 64){
decode[(int)base64[i]] = i;
}
while(1){
int n = 0, c, stopped_at = 4;
rep(i, 0, 4){
c = infile.get();
while(!((c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') ||
c == '+' ||
c == '/' ||
c == '=' ||
c == EOF)){
c = infile.get();
}
if(c == '=' || c == EOF){
stopped_at = i;
break;
}
n = n << 6;
n += decode[c];
}
switch(stopped_at){
case 4:
outfile.put((n>>16) & 0xff);
outfile.put((n>>8) & 0xff);
outfile.put(n & 0xff);
break;
case 3:
outfile.put((n>>8) & 0xff);
outfile.put(n & 0xff);
break;
case 2:
outfile.put(n & 0xff);
break;
}
if(c == EOF) break;
}
}
int main(int argc, char *argv[]){
if(argc < 2){
cout << "Wrong input argument, use " << argv[0] << " [-d] infile.\n";
return 0;
}
fstream infile;
fstream outfile;
if(argv[1][0] == '-' && argv[1][1] == 'd'){
infile.open(argv[2], fstream::in | fstream::binary);
outfile.open(argv[3], fstream::out | fstream::binary);
}
else{
infile.open(argv[1], fstream::in | fstream::binary);
outfile.open(argv[2], fstream::out | fstream::binary);
}
if(argv[1][0] == '-' && argv[1][1] == 'd')
decompress(infile, outfile);
else
compress(infile, outfile);
infile.close();
outfile.close();
return 0;
}