base64编解码

本文介绍了Base64编码的原理,通过举例说明如何将一个字节的二进制数据转换为Base64字符。内容涉及到位移操作和Base64字符集的使用,同时提到了Base64解码的过程。

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值