45 lines
1023 B
C++
45 lines
1023 B
C++
|
#pragma once
|
||
|
#include <string>
|
||
|
#include <vector>
|
||
|
|
||
|
typedef unsigned char uchar;
|
||
|
|
||
|
namespace base64 {
|
||
|
const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||
|
|
||
|
std::string Encode(const std::string &in)
|
||
|
{
|
||
|
std::string out;
|
||
|
int val = 0, valb = -6;
|
||
|
for (uchar c : in) {
|
||
|
val = (val << 8) + c;
|
||
|
valb += 8;
|
||
|
while (valb >= 0) {
|
||
|
out.push_back(base64_chars[(val >> valb) & 0x3F]);
|
||
|
valb -= 6;
|
||
|
}
|
||
|
}
|
||
|
if (valb > -6) out.push_back(base64_chars[((val << 8) >> (valb + 8)) & 0x3F]);
|
||
|
while (out.size() % 4) out.push_back('=');
|
||
|
return out;
|
||
|
}
|
||
|
|
||
|
std::string Decode(const std::string &in)
|
||
|
{
|
||
|
std::string out;
|
||
|
std::vector<int> T(256, -1);
|
||
|
for (int i = 0; i < 64; i++) T[base64_chars[i]] = i;
|
||
|
|
||
|
int val = 0, valb = -8;
|
||
|
for (uchar c : in) {
|
||
|
if (T[c] == -1) break;
|
||
|
val = (val << 6) + T[c];
|
||
|
valb += 6;
|
||
|
if (valb >= 0) {
|
||
|
out.push_back(char((val >> valb) & 0xFF));
|
||
|
valb -= 8;
|
||
|
}
|
||
|
}
|
||
|
return out;
|
||
|
}
|
||
|
}
|