随手练——十六进制转八进制 (不限制长度)
网上找了下,好像没有可以从十六进制直接转换到八进制的方法,一般就是转换成10进制或者2进制,再转换成8进制。
分两种情况,如果结果较小的话,用int、long long能装得下的情况下,用16→10→8比较方便:
#include <iostream> #include <algorithm> #include <math.h> #include <string> using namespace std; int to_10_system(string s) { int res = 0, k = 0; reverse(s.begin(), s.end()); for (int i = 0; i < s.length(); i++) { if (s[i] >= 'A'&&s[i] <= 'F') { switch (s[i]) { case 'A': res += pow(16, k++) * 10; break; case 'B': res += pow(16, k++) * 11; break; case 'C': res += pow(16, k++) * 12; break; case 'D': res += pow(16, k++) * 13; break; case 'E': res += pow(16, k++) * 14; break; case 'F': res += pow(16, k++) * 15; break; } } else { res += (s[i] - '0')*pow(16, k++); } } return res; } int to_8_system(int x) { int res = 0, i = 0; while (x) { res += (x % 8)*pow(10, i++); x /= 8; } return res; } int main() { int n; cin >> n; while (n--) { string s; cin >> s; cout << to_8_system(to_10_system(s))<<endl; } return 0; }
如果数据特别长的话,只能用字符串装的时候,还是16→2→8方便:
#include <iostream> #include <algorithm> #include <math.h> #include <string> using namespace std; string to_2_system(string s) { string res; int k = 0; for (int i = 0; i < s.length(); i++) { string t; //这里偷了个懒 *_* switch (s[i]) { case '0': t = "0000";break; case '1': t = "0001";break; case '2': t = "0010";break; case '3': t = "0011";break; case '4': t = "0100";break; case '5': t = "0101";break; case '6': t = "0110";break; case '7': t = "0111";break; case '8': t = "1000";break; case '9': t = "1001";break; case 'A': t = "1010";break; case 'B': t = "1011";break; case 'C': t = "1100";break; case 'D': t = "1101";break; case 'E': t = "1110";break; case 'F': t = "1111";break; } res += t; } while (res.length() % 3 != 0) { res.insert(res.begin(), '0'); } return res; } string to_8_system(string s) { string res; for (int i = s.length() - 1; i >= 0; i -= 3) { int t = s[i] - '0' + (s[i - 1] - '0') * 2 + (s[i - 2] - '0') * 4; if (!(i == 2 && t == 0)) res += t + '0'; } reverse(res.begin(), res.end()); return res; } int main() { int n; cin >> n; while (n--) { string s; cin >> s; cout << to_8_system(to_2_system(s))<<endl; } return 0; }