2024/3/13
//#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <bitset>
using namespace std;
void input(vector<string>& any_text)
{
string str,temp;
cout << "请输入文本:" << endl;
getline(cin,str);
stringstream str_stream(str);
while (str_stream >> temp)
any_text.push_back(temp);
}
void print(string text, vector<string> dec_text, vector<string> hex_text, vector<string> binary_text) {
// 打印文本内容
cout << "----------转化完成----------\n文本内容:\n" << text << endl;
// 打印各进制表示
vector<pair<string, vector<string>>> formats = {
{"十进制", dec_text},
{"十六进制", hex_text},
{"二进制", binary_text}
};
for (auto format : formats) {
cout << format.first << "表示:\n";
for (string value : format.second)
cout << value << " ";
cout << endl;
}
}
vector<string> text_to_dec(string text)
{
vector<string> dec_text;
for (auto w:text)
dec_text.push_back(to_string((int)w));
return dec_text;
}
vector<string> any_to_dec(vector<string> x_text, int x)
{
vector<string> dec_text;
for (string w:x_text)
dec_text.push_back(to_string(stoi(w,nullptr,x)));
return dec_text;
}
vector<string> dec_to_hex(vector<string> dec_text)
{
stringstream temp;
vector<string> hex_text;
for (string w:dec_text)
{
temp << hex << stoi(w);
hex_text.push_back(temp.str());
temp.str("");
}
return hex_text;
}
vector<string> dec_to_binary(vector<string> dec_text)
{
stringstream temp;
vector<string> binary_text;
for (string w:dec_text)
{
temp << bitset<sizeof(int) * 4>(stoi(w));
binary_text.push_back(temp.str());
temp.str("");
}
return binary_text;
}
string dec_to_text(vector<string> dec_text)
{
stringstream temp;
for (string w:dec_text)
temp << static_cast<char>(stoi(w));
return temp.str();
}
int main()
{
int num = 0;
string t_text;
vector<string> h_text, d_text, b_text;
cout << "请选择你要输入的类型的序号:\n1、text\n2、hex\n3、dec\n4、binary\n----------\n输入序号:";
cin >> num; cin.get();
switch(num)
{
case 1:
cout << "请输入文本:" << endl;
getline(cin,t_text);
d_text = text_to_dec(t_text);
h_text = dec_to_hex(d_text);
b_text = dec_to_binary(d_text);
break;
case 2:
input(h_text);
d_text = any_to_dec(h_text,16);
b_text = dec_to_binary(d_text);
t_text = dec_to_text(d_text);
break;
case 3:
input(d_text);
h_text = dec_to_hex(d_text);
b_text = dec_to_binary(d_text);
t_text = dec_to_text(d_text);
break;
case 4:
input(b_text);
d_text = any_to_dec(b_text,2);
h_text = dec_to_hex(d_text);
t_text = dec_to_text(d_text);
break;
default:
cout << "输入错误" <<endl;
break;
}
print(t_text, d_text, h_text,b_text);
}
运行结果展示: