Base64编码
这里的Base64编码是基于ASCILL编码表来设定的,如果超过一个字节(8位)则重新研究研究,这里顺带提一下怎么算Base64的,我们以h为例:
h biniray 0110 1000
h >> 2 & 0x3F = 0001 1010
00001 1010 = uint32_t(26)
base64 charsets(“ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/”) 查找26下表并且取出值 = a
h << 2 & 0x3F
0001 1010 0000 & 0000 0011 1111 = 00 0000 find charsets A
公式:8l >> 2l == 6l + 2l + ‘=’ +’=’
结果aA==
#include <iostream>
#include <string>
std::string base64_encode(const std::string& in)
{
static const auto lookup =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string out;
out.reserve(in.size());
int val = 0;
int valb = -6;
for (auto c : in)
{
val = (val << 8) + static_cast<uint8_t>(c);
valb += 8;
while (valb >= 0)
{
out.push_back(lookup[(val >> valb) & 0x3F]);
valb -= 6;
}
}
if (valb > -6)
{
out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]);
while (out.size() % 4) {
out.push_back('=');
}
return out;
}
}
int main()
{
std::string base64 = base64_encode("wori");
std::cout << base64 << std::endl;
std::cin.get();
return 1;
}
Base64解码
inline std::string bease64_decode(const std::string& in) {
static const std::string lookup("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
std::string out;
out.reserve(in.size());
int val = 0;
int valb = -8;
for (auto c : in)
{
std::string::size_type index = lookup.find(c);
if (index != std::string::npos) {
val = (val << 6) + static_cast<uint8_t>(index);
valb += 6;
if (valb < 0)continue;
out.push_back((char)((val >> valb) & 0xFF));
valb -= 8;
}
}
return out;
}
本文介绍了Base64编码的原理,通过举例说明如何将一个字节的二进制数据转换为Base64字符。内容涉及到位移操作和Base64字符集的使用,同时提到了Base64解码的过程。
2778

被折叠的 条评论
为什么被折叠?



