四、阅读程序-3
假设输入总是合法的(一个整数和一个不含空白字符的字符串,用空格隔开),完成下面的判断题和单选题:
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 | #include <iostream> #include <string> using namespace std; char base[64]; char table[256]; void init() { for (int i = 0; i < 26; i++) base[i] = 'A' + i; for (int i = 0; i < 26; i++) base[26 + i] = 'a' + i; for (int i = 0; i < 10; i++) base[52 + i] = '0' + i; base[62] = '+', base[63] = '/'; for (int i = 0; i < 256; i++) table[i] = 0xff; for (int i = 0; i < 64; i++) table[base[i]] = i; table['='] = 0; } string encode(string str) { string ret; int i; for (i = 0; i + 3 <= str.size(); i += 3) { ret += base[str[i] >> 2]; ret += base[(str[i] & 0x03) << 4 | str[i + 1] >> 4]; ret += base[(str[i + 1] & 0x0f) << 2 | str[i + 2] >> 6]; ret += base[str[i + 2] & 0x3f]; } if (i < str.size()) { ret += base[str[i] >> 2]; if (i + 1 == str.size()) { ret += base[(str[i] & 0x03) << 4]; ret += "=="; } else { ret += base[(str[i] & 0x03) << 4 | str[i + 1] >> 4]; ret += base[(str[i + 1] & 0x0f) << 2]; ret += "="; } } return ret; } string decode(string str) { string ret; int i; for (i = 0; i < str.size(); i += 4) { ret += table[str[i]] << 2 | table[str[i + 1]] >> 4; if (str[i + 2] != '=') ret += (table[str[i + 1]] & 0x0f) << 4 | table[str[i + 2]] >> 2; if (str[i + 3] != '=') ret += (table[str[i + 2]] & 0x3f) << 6 | table[str[i + 3]]; } return ret; } int main() { init(); cout << int(table[0]) << endl; int opt; string str; cin >> opt >> str; cout << (opt ? decode(str) : encode(str)) << endl; return 0; } |
