任意进制间的转换
以前只是研究某两个进制A,B之间的转化,现在推广到任意进制。
其中十进制转为B进制:除B取余,倒序排列目前的缺点是不能算小数和负数。
#include <bits/stdc++.h> using namespace std; int toTen(const string & old, const int base) { int res = 0; for(size_t i = 0; i != old.length(); i++) { if(isupper(old[i])) res = res * base + old[i] - 'A' + 10; else if(islower(old[i])) res = res * base + old[i] - 'a' + 10; else res = res * base + old[i] - '0'; } return res; } deque<char> Tento(int ten, const int base) { deque<char> res; while(ten > 0){ int t = ten % base; res.push_front(t>=10 ? (char)(t-10+'A') : (char)(t+'0')); ten /= base; } return res; } int main() { int x, y, ten; string old; printf("输入原数:"); cin >> old; printf("输入原数进制:"); cin >> x; printf("输入要转换到的进制:"); cin >> y; ten = toTen(old, x); deque<char> res = Tento(ten, y); for(size_t i = 0; i != res.size(); i++) printf("%c", res[i]); printf("\n"); return 0; }