Skip to content

Instantly share code, notes, and snippets.

@williamdes
Created June 20, 2017 16:40
Show Gist options
  • Save williamdes/308b95ac9ef1ee89ae0143529c361d37 to your computer and use it in GitHub Desktop.
Save williamdes/308b95ac9ef1ee89ae0143529c361d37 to your computer and use it in GitHub Desktop.
c++ 11 encoding and decoding base64
//FROM
//https://stackoverflow.com/a/34571089/5155484
typedef unsigned char uchar;
static const std::string b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";//=
static std::string base64_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(b[(val>>valb)&0x3F]);
valb-=6;
}
}
if (valb>-6) out.push_back(b[((val<<8)>>(valb+8))&0x3F]);
while (out.size()%4) out.push_back('=');
return out;
}
static std::string base64_decode(const std::string &in) {
std::string out;
std::vector<int> T(256,-1);
for (int i=0; i<64; i++) T[b[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;
}
@mcordova1967
Copy link

Very nice, it worked right away. Thank you for sharing it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment