base64编码
base64编码:
//
// Created by Harold on 2022/8/14/0014.
//
#include <iostream>
#include <string>
#include <vector>
#define MAX_SIZE 1000
using namespace std;
class Solution{
public:
void getInput(){
cin>>codeList;
}
void getTheAns(){
int startIndex = 0, endIndex;
int codeLen = codeList.size();
if(codeLen <= 0){
cout<<"";
}
while(startIndex < codeLen){
if(startIndex + 2 < codeLen){
endIndex = startIndex + 2;
}
else{
endIndex = codeLen - 1;
}
decode(codeList.substr(startIndex,endIndex+1));
startIndex = endIndex + 1;
}
cout<<base64StrList;
}
void run(){
getInput();
getTheAns();
}
void decode(string subCode){
vector<int> base64(4,0);
int subCodeLen = subCode.size();
string res(4,'0');
base64[0] = int(subCode[0]) >> 2; // 取第一个字节前6位(通过右移两位)
if(subCodeLen == 1){
base64[1] = ((int(subCode[0]) & 0x03) << 4);
base64[2] = MAX_SIZE;
base64[3] = MAX_SIZE;
}
else if(subCodeLen == 2){
base64[1] = ((int(subCode[0]) & 0x03) << 4) + (int(subCode[1]) >> 4);
base64[2] = ((int(subCode[1]) & 0x0f) << 2);
base64[3] = MAX_SIZE;
}
else if(subCodeLen == 3){
base64[1] = ((int(subCode[0]) & 0x03) << 4) + (int(subCode[1]) >> 4); // 取第一个字节后2位作为高位,第二个字节前4位作为低位
base64[2] = ((int(subCode[1]) & 0x0f) << 2) + (int(subCode[2]) >> 6);
base64[3] = (int(subCode[2]) & 0x3f);
}
else{
cout<<"error !\n";
return;
}
for(int i = 0; i < base64.size(); i++){
if(0 <= base64[i] && base64[i] <= 25){
res[i] = char('A' + base64[i]);
}
else if(26 <= base64[i] && base64[i] <= 51){
res[i] = char('a' + base64[i] - 26);
}
else if(52 <= base64[i] && base64[i] <=61){
res[i] = char('0' + base64[i] - 52);
}
else if(base64[i] == 62){
res[i] = '+';
}
else if(base64[i] == 63){
res[i] = '/';
}
else if(base64[i] == MAX_SIZE){
res[i] = '=';
}
else{
cout<<"error !\n";
return;
}
}
base64StrList += res;
}
private:
string codeList;
string base64StrList;
};
int main(){
Solution s;
s.run();
} 