进制转换
快捷方法
printf("%o", x); // 以8进制输出
printf("%d", x); // 以10进制输出
printf("%x", x); // 以16进制输出
cin >> hex >> x; // hex以16进制形式读入
cout << x; // 默认以10进制形式输出
cout << hex << x; // 以16进制输出
cout << dec << x; // 以10进制输出
cout << oct << x; // 以8进制输出
cout << bitset<8>(x); // 以2进制输出保留<8>位输出
库函数
itoa(num, str, 2); // num是一个int型的,是要转化的10进制数,str是转化结果,后面的值为目标进制。
#include<cstdio>
#include<cstdlib>
int main()
{
int num = 10;
char str[100];
_itoa(num, str, 2);
printf("%s\n", str);
return 0;
}
来源连接 https://blog.csdn.net/vir_lee/article/details/80645066
16进制转8进制
#include <iostream>
#include <cstring>
using namespace std;
string ans[15];
int main()
{
int n;
cin >> n;
while (n --)
{
string str;
cin >> str;
string res1 = "";
// 转为二进制
for (int i = 0; i < str.size(); i ++ )
{
switch(str[i])
{
case '0' : res1 += "0000"; break;
case '1' : res1 += "0001"; break;
case '2' : res1 += "0010"; break;
case '3' : res1 += "0011"; break;
case '4' : res1 += "0100"; break;
case '5' : res1 += "0101"; break;
case '6' : res1 += "0110"; break;
case '7' : res1 += "0111"; break;
case '8' : res1 += "1000"; break;
case '9' : res1 += "1001"; break;
case 'A' : res1 += "1010"; break;
case 'B' : res1 += "1011"; break;
case 'C' : res1 += "1100"; break;
case 'D' : res1 += "1101"; break;
case 'E' : res1 += "1110"; break;
case 'F' : res1 += "1111"; break;
}
}
switch (res1.size()%3)
{
case 1: res1 = "00" + res1; break;
case 2: res1 = "0" + res1; break;
}
string res2 = "";
for (int i = 0; i < res1.size(); i += 3)
{
string t = res1.substr(i, 3);
if (i == 0 && t == "000") continue;
else res2 += (4*(t[0] - '0') + 2 * (t[1] - '0') + (t[2] - '0')) + '0';
}
cout << res2 << endl;
}
return 0;
}
10进制转16进制
#include <iostream>
using namespace std;
typedef long long LL;
char a[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
int main()
{
LL n;
cin >> n;
string str = "";
if (n == 0) puts("0");
else
{
while (n)
{
str += a[n%16];
n /= 16;
}
}
for (int i = str.size() - 1; i >= 0; i -- ) cout << str[i];
return 0;
}