1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| #include<iostream> #include<String> #include<cstdlib> #include <vector>
std::string en(std::string str) { using namespace std; const string table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; std::vector<uint8_t> input; std::vector<uint8_t> output; for (char c : str) { input.push_back(c); }
const uint8_t len_before = str.length(); uint8_t fix_num = 0; switch (len_before % 3) { case 1: fix_num++; case 2: fix_num++; } for (int i = 0; i < fix_num; i++) { input.push_back('\0'); } uint8_t save[4] = {};
for (int i = 0; i < len_before; i += 3) { save[0] = input[i] >> 2; output.push_back(table[save[0]]); save[1] = (input[i] & 0b00000011) << 4 | input[i + 1] >> 4; output.push_back(table[save[1]]); save[2] = (input[i + 1] & 0b00001111) << 2 | input[i + 2] >> 6; save[3] = input[i + 2] & 0b00111111; output.push_back(table[save[2]]); output.push_back(table[save[3]]); } if (output.back() == table[0]) { for (int i = 0; i < fix_num; i++) { output.pop_back(); } for (int i = 0; i < fix_num; i++) { output.push_back(table[64]); } } string res(output.begin(), output.end()); return res; }
std::string de(std::string str) { using namespace std; const string table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; vector<uint8_t> input; vector<uint8_t> output; for (char c : str) { input.push_back(table.find(c)); } for (int i = 0; i < input.size(); i += 4) { output.push_back((input[i] << 2) | (input[i + 1] >> 4)); if (input[i + 2] != 64) { output.push_back((input[i + 1] << 4) | (input[i + 2] >> 2)); } if (input[i + 3] != 64) { output.push_back((input[i + 2] << 6) | input[i + 3]); } } string res(output.begin(), output.end()); return res; }
int main(void) { using namespace std; cout << "please use Ctrl+Z to quit\n"; cout << "please input your string:\n";
string str; while (getline(cin, str)) { cout << en(str) << endl << de(en(str)) << endl; cout << "\nplease input your string:\n"; } return 0;
}
|