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();
}



#大疆笔试##算法题#
全部评论
事后诸葛亮
1 回复 分享
发布于 2022-08-14 22:13

相关推荐

06-07 17:17
嘉兴学院 教师
心爱的idea:你孩
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-04 14:35
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务