进制转换
进制转换(最大支持62进制)
很久之前就一直想搞这个东西,一直没有做出来,今天心血来潮写了出来。
因为中间存储数据的是long long
所以如果一个进制表达的数字超出范围就无法转换了
Code
#include <bits/stdc++.h>
using namespace std;
class NumConversion
{
private:
long long _int_num;
int _in_sys = 10;
int _out_sys = 10;
stack<int> tmp;
string _in_num;
string _out_num;
map<char, int> alpha_num;
vector<char> num_alpha =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
public:
NumConversion()
{
for (int i = 0; i < 62; i++)
{
if (i < 10)
alpha_num['0' + i] = i;
else if (i < 36)
alpha_num['a' + i - 10] = i;
else
alpha_num['A' + i - 36] = i;
}
}
long long num_to_dec_int(string num)
{
_in_num = num;
int k = 1;
long long ans = 0;
for (int i = _in_num.length() - 1; i >= 0; i--)
{
char c = _in_num[i];
ans += alpha_num[c] * k;
k *= _in_sys;
}
return ans;
}
string dec_int_to_num(long long num)
{
_out_num.clear();
while (num)
{
tmp.push(num % _out_sys);
num /= _out_sys;
}
while (!tmp.empty())
{
_out_num.push_back(num_alpha[tmp.top()]);
tmp.pop();
}
return _out_num;
}
void set_num_sys(int in, int out)
{
_in_sys = in;
_out_sys = out;
}
string num_converse(string num, int in, int out)
{
set_num_sys(in, out);
_int_num = num_to_dec_int(num);
return dec_int_to_num(_int_num);
}
};
int main()
{
NumConversion *obj = new NumConversion();
char c;
while (c != 'n')
{
string num;
int in;
int out;
cout << "input number system:\t";
cin >> in;
cout << "output number system:\t";
cin >> out;
string add = "";
if (in == 10)
add = "(dec)";
else if (in == 8)
add = "(oct)";
else if (in == 2)
add = "(bin)";
else if (in == 16)
add = "(hex)";
cout << "input your number:\t" << add;
cin >> num;
if (out == 10)
add = "(dec)";
else if (out == 8)
add = "(oct)";
else if (out == 2)
add = "(bin)";
else if (out == 16)
add = "(hex)";
cout << "answer is:\t\t" << add << obj->num_converse(num, in, out) << endl;
cout << "continue?(y/n): ";
cin >> c;
cout << endl;
}
return 0;
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 GZTime's Blog!
评论