十进制转化为二进制
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1000;
int a[N], cnt;
int main() {
int n;
while (cin >> n) {
cnt = 0;
do {
a[cnt++] = n % 2;
n /= 2;
} while (n != 0);
for (int i = cnt - 1; i >= 0; i--) {
cout << a[i];
}
}
return 0;
}
十进制转换为十六进制
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1000;
int a[N], cnt;
char h[17] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; // 记录十六进制的各个数
int main() {
int n;
while (cin >> n) {
cnt = 0;
do {
a[cnt++] = n % 16;
n /= 16;
} while (n != 0);
for (int i = cnt - 1; i >= 0; i--) {
int k = a[i];
cout << h[k];
}
}
return 0;
}
任意进制数之间的转换
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int T;
cin>>T;
while(T--)
{
int a,b;
string a_line, b_line;
cin >> a >> b >> a_line;
// b是将要转换的进制
vector<int> number;
// 把字母转换为数字便于计算
for(auto c : a_line)
{
if(c >= '0' && c <= '9') number.push_back(c - '0');
if(c >= 'A' && c <= 'Z') number.push_back(c-'A' + 10);
if(c >= 'a' && c <= 'z') number.push_back(c -'a' + 36);
}
reverse(number.begin(),number.end()); // 低位在前,高位在后 ![](https://)
vector<int> res;
while(number.size())
{
int r = 0;
for(int i = number.size()-1; i >= 0;i--) // 除法从高位开始算起
{
number[i] += r * a; // 加上高位的余数*a进制
r = number[i] % b;
number[i] /= b;
}
res.push_back(r);
while(number.size() && number.back()==0) number.pop_back(); // 把前面的0去掉
}
reverse(res.begin(),res.end()); // 求得得进制数
for(int i = 0;i < res.size();i++)
{
int a = res[i];
if(a >= 0 && a <= 9) b_line += char(a + '0');
if(a >= 10 && a <= 35) b_line += char(a - 10 + 'A');
if(a >= 36) b_line += char(a - 36 + 'a');
}
cout << a << " "<< a_line<<endl;
cout << b << " "<<b_line << endl;
cout << endl;
}
return 0;
}
步骤理解
很不错,收藏了
好的