Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
alexbevi
GitHub Repository: alexbevi/BizHawk
Path: blob/master/libsnes/bsnes/nall/base64.hpp
2 views
1
#ifndef NALL_BASE64_HPP
2
#define NALL_BASE64_HPP
3
4
#include <string.h>
5
#include <nall/stdint.hpp>
6
7
namespace nall {
8
struct base64 {
9
static bool encode(char *&output, const uint8_t* input, unsigned inlength) {
10
output = new char[inlength * 8 / 6 + 6]();
11
12
unsigned i = 0, o = 0;
13
while(i < inlength) {
14
switch(i % 3) {
15
case 0: {
16
output[o++] = enc(input[i] >> 2);
17
output[o] = enc((input[i] & 3) << 4);
18
} break;
19
20
case 1: {
21
uint8_t prev = dec(output[o]);
22
output[o++] = enc(prev + (input[i] >> 4));
23
output[o] = enc((input[i] & 15) << 2);
24
} break;
25
26
case 2: {
27
uint8_t prev = dec(output[o]);
28
output[o++] = enc(prev + (input[i] >> 6));
29
output[o++] = enc(input[i] & 63);
30
} break;
31
}
32
33
i++;
34
}
35
36
return true;
37
}
38
39
static bool decode(uint8_t *&output, unsigned &outlength, const char *input) {
40
unsigned inlength = strlen(input), infix = 0;
41
output = new uint8_t[inlength]();
42
43
unsigned i = 0, o = 0;
44
while(i < inlength) {
45
uint8_t x = dec(input[i]);
46
47
switch(i++ & 3) {
48
case 0: {
49
output[o] = x << 2;
50
} break;
51
52
case 1: {
53
output[o++] |= x >> 4;
54
output[o] = (x & 15) << 4;
55
} break;
56
57
case 2: {
58
output[o++] |= x >> 2;
59
output[o] = (x & 3) << 6;
60
} break;
61
62
case 3: {
63
output[o++] |= x;
64
} break;
65
}
66
}
67
68
outlength = o;
69
return true;
70
}
71
72
private:
73
static char enc(uint8_t n) {
74
//base64 for URL encodings
75
static char lookup_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
76
return lookup_table[n & 63];
77
}
78
79
static uint8_t dec(char n) {
80
if(n >= 'A' && n <= 'Z') return n - 'A';
81
if(n >= 'a' && n <= 'z') return n - 'a' + 26;
82
if(n >= '0' && n <= '9') return n - '0' + 52;
83
if(n == '-') return 62;
84
if(n == '_') return 63;
85
return 0;
86
}
87
};
88
}
89
90
#endif
91
92