C++实现base64编码

关于Base64编码
解码为逆过程,有空就写

#include<bits/stdc++.h>

using namespace std;

char base[]= {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
              'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
              '0','1','2','3','4','5','6','7','8','9','+','/'
             };

string to_bin(char c)//字符转二进制字符串 
{
	int n=c;
	string bin;
	for (int i=7; i>=0; i--)
	{
		bin+=((n>>i)&1)+'0';
	}
	return bin;
}

char base_char(string s)//6位字符串转base64字符
{
	int num=bitset<6> (s).to_ullong();
	return base[num];
}

string to_base(string s)
{
	string res;
	int cnt=0;//base64以4个为一组,cnt统计字符个数,不是4的倍数加'='补齐
	int len=s.size();
	for(int i=0; i*6+6<=len; i++)//6个6个一组转化为base64字符 
	{
		cnt++;
		string tmp=s.substr(i*6,6);
		res+=base_char(tmp);
	}
	int rest=s.size()%6;
	if(rest!=0)//对剩余字符串小于六位补0
	{
		string end=s.substr(len-rest);
		while(end.size()<6)
			end+='0';
		cnt++;
		res+=base_char(end);
	}
	int eq=cnt%4;
	if(eq!=0)//补齐使其成为base64编码
		for(int i=eq; i<4; i++)
			res+='=';
	return res;
}

int main()
{
	string s;
	cin>>s;
	string bin,res;
	for(auto i:s)//每个字符都转化为二进制字符串 
	{
		bin+=to_bin(i);
	}
	res=to_base(bin);//转化为base64编码 
	cout<<res;
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C++实现base64编码的示例代码: ```c++ #include <iostream> #include <string> #include <vector> std::string base64_encode(const std::string& input) { std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string output; int bits = 0; int bit_count = 0; unsigned char ch = 0; for (const auto& c : input) { ch = c; bits = (bits << 8) | ch; bit_count += 8; while (bit_count >= 6) { bit_count -= 6; ch = (bits >> bit_count) & 0x3f; output += base64_chars[ch]; } } if (bit_count > 0) { bits = bits << (6 - bit_count); ch = bits & 0x3f; output += base64_chars[ch]; while (bit_count < 6) { output += '='; bit_count += 2; } } return output; } int main() { std::string input = "Hello, world!"; std::string encoded = base64_encode(input); std::cout << encoded << std::endl; return 0; } ``` 在这个示例代码中,我们定义了一个 `base64_encode` 函数,它接受一个字符串作为输入,并返回一个编码过的字符串。在实现中,我们使用了一个 `base64_chars` 字符串来存储可用的字符。我们遍历输入字符串,并将每个字符转换为一个 8 位的整数,然后将这些整数合并为一个大的整数。我们将大的整数分成 6 位的块,并将每个块转换为一个可用的字符。最后,我们将所有字符连接起来,形成编码过的字符串。如果输入字符串的长度不是三的倍数,我们将使用 `=` 字符进行填充,使其长度变为三的倍数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值