#include<iostream>
#include<vector>
#include<unordered_set>
using namespace std;
int numToBase64(int num) { //按数字转为Base64编码
char c;
if (num >= 62) {
if (num == 62) {
c = '+';
}
else {
c = '/';
}
}
else if (0 <= num && num <= 25) {
c = num + 'A';
}
else if (26 <= num && num <= 51) {
c = num - 26 + 'a';
}
else {
c = num - 52 + '0';
}
return c;
}
void printB(int num) { //显示二进制数
int i = 0b10000000;
while (i) {
if (num & i) {
cout << '1';
}
else {
cout << '0';
}
i = i >> 1;
}
cout << endl;
}
int main() {
string input = "254ASDF1";
string res;
int n = input.size();
int pre = 0;
int cur = 0;
for (int i = 0; i < n; ++i) {
cur = input[i];
printB(cur);
if (i % 3 == 0) {
pre = cur & 3; //剩2位
cur = (cur & 0b11111100) >> 2; // 用6位
res.push_back(numToBase64(cur));
}
else if (i % 3 == 1) {
//cur = pre * 16 + cur / 16;
cur = (pre << 4) + (cur >> 4); //需要注意的问题:左移和右移运算优先级低于+-符号的运算,因此此处会先计算加法
res.push_back(numToBase64(cur)); //用4位
pre = input[i] & 0b00001111; //剩4位
}
else {
cur = pre * 4 + cur / 64; //用2位
pre = input[i] & 0b00111111; //剩6位
res.push_back(numToBase64(cur));
cur = pre; //用6位
pre = 0;
res.push_back(numToBase64(cur));
}
cout << "输出:" << cur << " ";
printB(cur);
cout << "保留:" << pre << " ";
printB(pre);
}
if (n % 3 == 1) { // 只剩一个字节,上面先处理了1个base64数,还差3个
cur = pre * 16;
pre = 0;
res.push_back(numToBase64(cur));
res.push_back('=');
res.push_back('=');
}
else if(n % 3 == 2) { // 只剩2个字节,上面处理了2个base64数,还差2个
cur = pre * 4;
pre = 0;
res.push_back(numToBase64(cur));
res.push_back('=');
}
cout << res <<endl;
//下面为测试运算符优先级问题
int temp = 1;
int temp2 = 4;
//int temp3 = temp << 1 + temp2 >> 1; // 先计算1+temp2 = 5, temp左移5位,再右移1位;
cout << temp3;
return 0;
}
10-27
1337
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)