What is base64 coding and decoding are in reference to
Https://en.wikipedia.org/wiki/Base64
Http://www.cnblogs.com/chengxiaohui/articles/3951129.html
Sample code in C + +. Please note that the code needs refinements as there are some warning in some analysis tools,e.g. Pc-lint, Coverity etc.
It is just a, sample code for study.
declaration in header
std::string base64encode (const std::vector<char>& bytedata);
Std::vector<char> Base64decode (std::string & const inputstring);
Implemenation
std::string cbase64dlg::base64encode (const std::vector<char>& bytedata)
{
Const std::string codes = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/=";
Std::string base64string;
int b;
for (size_t i = 0; i < bytedata.size (); i = i+3)
{
b = (Bytedata[i] & 0xFC) >> 2;
Base64string.push_back (Codes[b]);
b = (Bytedata[i] & 0x03) << 4;
if (i + 1 < bytedata.size ())
{
b |= (bytedata[i + 1] & 0xF0) >> 4;
Base64string.push_back (Codes[b]);
B = (bytedata[i + 1] & 0x0F) << 2;
if (I+2 < Bytedata.size ())
{
b |= (Bytedata[i + 2] & 0xC0) >> 6;
Base64string.push_back (Codes[b]);
b = Bytedata[i + 2] & 0x3F;
Base64string.push_back (Codes[b]);
}
Else
{
Base64string.push_back (Codes[b]);
Base64string.append ("=");
}
}
Else
{
Base64string.push_back (Codes[b]);
Base64string.append ("= =");
}
}
return base64string;
}
Std::vector<char> Cbase64dlg::base64decode (std::string & const inputstring)
{
static std::string codes = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/=";
Std::vector<char> Decoded;
if (inputstring.length ()% 4! = 0)
{
return std::vector<char> ();
}
The ratio of output bytes to input bytes is 4:3
int Outlen = (inputstring.length () * 3/4);
size_t pos = inputstring.find_first_of (' = ');
if (pos! = std::string::npos)
{
Decoded.resize (Outlen-(Inputstring.length ()-POS));
}
Else
{
Decoded.resize (Outlen);
}
int j = 0;
int b[4] = {};
Const char* p = inputstring.c_str ();
while (P && *p && J < Outlen)
{
bool valid = FALSE;
for (int i=0; p && i < 4; ++i)
{
size_t pos = codes.find_first_of (*p++);
if (pos! = std::string::npos)
{
B[i] = pos;
}
}
if (J < Outlen)
{
Decoded[j++] = (byte) ((B[0] << 2) | (B[1] >> 4));
if (J < Outlen && B[2] < 64)
{
Decoded[j++] = (byte) ((B[1] << 4) | (B[2] >> 2));
if (J < Outlen && B[3] < 64)
{
Decoded[j++] = (byte) ((B[2] << 6) | b[3]);
}
}
}
}
return decoded;
}
Test code
Char myints[] = "abc&&&&&&&&&&";
Std::vector<char> byte (myints, myints + sizeof (myints)/sizeof (char));
std::string value = Base64Encode (byte);
Std::cout << value << Std::endl;
Std::vector<char>decode = Base64decode (value);
BASE64 encoding and decoding