任意进制间的转换
以前只是研究某兩個(gè)進(jìn)制A,B之間的轉(zhuǎn)化,現(xiàn)在推廣到任意進(jìn)制。
其中十進(jìn)制轉(zhuǎn)為B進(jìn)制:除B取余,倒序排列目前的缺點(diǎn)是不能算小數(shù)和負(fù)數(shù)。
#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("輸入原數(shù):"); cin >> old;printf("輸入原數(shù)進(jìn)制:"); cin >> x;printf("輸入要轉(zhuǎn)換到的進(jìn)制:"); 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; }
轉(zhuǎn)載于:https://www.cnblogs.com/kunsoft/p/5312751.html
總結(jié)
- 上一篇: js关联数组
- 下一篇: 超简易复制Model对象(为后续备忘录设