#include<iostream>
#include<string>
using namespace std;
string printbinary(int val){
string bin;
int s = val;
int y = s%16;
if( s == 0){
bin = ‘0‘;
return bin;
}
while(s != 0){
if(y >= 0 && y <= 9)
bin += y + ‘0‘;
else{
y = y - 10;
bin += y + ‘A‘;
}
s = s/16;
y = s%16;
}
return bin;
}
string reversedOrder(string bin){
int len = bin.length();
char temp;
for(int j=0;j<len/2;j++)
{
temp = bin[j];
bin[j] = bin[len-1-j];
bin[len-1-j] = temp;
}
return bin;
}
int main()
{
int dec;
cin>>dec;//输入十进制数
string bin = printbinary(dec);//十进制转化为十六进制
bin = reversedOrder(bin);//将十六进制进行逆序
cout << bin << endl;
return 0;
}
#include<iostream>
#include<string>
using namespace std;
string printbinary(int val){
string bin;
int s = val;
while(s != 0){
if(s%2 == 0)
bin = bin + ‘0‘;
else
bin = bin + ‘1‘;
s = s/2;
}
return bin;
}
string reversedOrder(string bin){
int len = bin.length();
char temp;
for(int j=0;j<len/2;j++)
{
temp = bin[j];
bin[j] = bin[len-1-j];
bin[len-1-j] = temp;
}
return bin;
}
string binToHex(string bin){
int len = bin.length();
int num = 0;
int temp = 4;
string hex;
for(int j=len-1;j>=0;j--)
{
if(bin[j] == ‘1‘)
{
switch(temp)
{
case 4: num +=1;break;
case 3: num +=2;break;
case 2: num +=4;break;
case 1: num +=8;break;
default:break;
}
}
temp--;
if(temp == 0)
{
if(num > 9)
hex += num - 10 + ‘A‘;
else
hex += num + ‘0‘;
num = 0;
temp = 4;
}
}
if(temp != 0)
{
if(num > 9)
hex += num - 10 + ‘A‘;
else
hex += num + ‘0‘;
}
return hex;
}
int main()
{
int dec;
cin>>dec;//输入十进制数
string bin = printbinary(dec);//十进制转化为二进制
bin = reversedOrder(bin);//将二进制进行逆序
bin = binToHex(bin);//二进制转化为十六进制
bin = reversedOrder(bin);//将十六进制进行逆序
cout << bin << endl;
return 0;
}
十进制转十六进制 【第一个方法蓝桥杯练习系统测试100分,第二个方法测试72分】
原文:http://www.cnblogs.com/HuangAQiu/p/6366272.html