C++ base64_encode function



#include <iostream>
#include <sstream>
 
using std::cout;
using std::endl;
 
std::string base64_encode(const std::string &s);
 
int main(int argc, char *argv[])
{
    cout << base64_encode("a") << endl;    //YQ==
    cout << base64_encode("ab") << endl;   //YWI=
    cout << base64_encode("abc") << endl;  //YWJj
    cout << base64_encode("abcd") << endl; //YWJjZA==
    cout << base64_encode("abcde") << endl; //YWJjZGU=
    cout << base64_encode("abcdef") << endl; //YWJjZGVm
    return 0;
}
 
std::string base64_encode(const std::string &s)
{
    static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    size_t i=0,ix=0,leng = s.length();
    std::stringstream q;
 
    for(i=0,ix=leng - leng%3; i<ix; i+=3)
    {
        q<< base64_chars[ (s[i] & 0xfc) >> 2 ];
        q<< base64_chars[ ((s[i] & 0x03) << 4) + ((s[i+1] & 0xf0) >> 4)  ];
        q<< base64_chars[ ((s[i+1] & 0x0f) << 2) + ((s[i+2] & 0xc0) >> 6)  ];
        q<< base64_chars[ s[i+2] & 0x3f ];
    }
    if (ix<leng)
    {
        q<< base64_chars[ (s[ix] & 0xfc) >> 2 ];
        q<< base64_chars[ ((s[ix] & 0x03) << 4) + (ix+1<leng ? (s[ix+1] & 0xf0) >> 4 : 0)];
        q<< (ix+1<leng ? base64_chars[ ((s[ix+1] & 0x0f) << 2) ] : '=');
        q<< '=';
    }
    return q.str();
}
code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)