用户输入三个字符,每个字符取值范围是0-9,A-F。然后程序会把这三个字符转化为相应的十六进制整数,并分别以十六进制,十进制,八进制输出,十六进制表示成3位,八进制表示成4位,若不够前面补0。(不考虑输入不合法的情况)
输入
1D5
输出
(注意冒号后面有一个空格)
Hex: 0x1D5
Decimal: 469
Octal: 0725
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
int main() {
string s;
cin >> s;
int len = s.length();
map<char, int> a;
a['0'] = 0;
a['1'] = 1;
a['2'] = 2;
a['3'] = 3;
a['4'] = 4;
a['5'] = 5;
a['6'] = 6;
a['7'] = 7;
a['8'] = 8;
a['9'] = 9;
a['A'] = 10;
a['B'] = 11;
a['C'] = 12;
a['D'] = 13;
a['E'] = 14;
a['F'] = 15;
int num = 0;
for (int i = 0; i <len; i++) {
num = num * 16 + a[s[i]];
}
cout << "Hex: 0x" << s<<endl;
cout << "Decimal: "<<num<<endl;
int oc[30];
int cnt = 0;
while (num != 0) {
oc[cnt++] = num % 8;
num = num / 8;
}
cout << "Octal: ";
for (int i =4; i > cnt; i--) {
cout << "0";
}
for (int i = cnt-1; i >= 0; i--) {
cout << oc[i];
}
cout << endl;
cin >> s;
return 0;
}