十进制转十六进制 代码

 

5621转换为16进制数的方法是“除16取余”方法, 
5621/16=商351余5,16进制最后一位为5 
351/16=商21余15,16进制右边第二位为F 
21/16=商1余5,16进制右边第三位为5 
1/16=商0余1,16进制数右边第四为为1 
商0就不继续除了  
最后的结果为15F5
#include <iostream>
#include <string>

using namespace std;

// 整数转换成字符串
string  int2str( int  num);

 
int main(int argc, char* argv[])
{
	// 十进制转十六进制
	int num = 0;
	cout<<"Please Input A Num "<<endl;
	cin>>num;
	string str_num;
	while(num / 16 != 0)
	{
		int a = num / 16;
		int mod_a = num % 16;
		cout<<"mod_a = "<<mod_a<<endl;
		string s;
		switch(mod_a)
		{
		case 10:
			s = 'A';
			break;
		case 11:
			s = 'B';
			break;
		case 12:
			s = 'C';
			break;
		case 13:
			s = 'D';
			break;
		case 14:
			s = 'E';
			break;
		case 15:
			s = 'F';
			break;
		default:
			s = int2str(mod_a);
			break;
		}
		str_num = s + str_num;
		num = a;
	}
	if(num % 16 != 0)
	{
		int last_a = num % 16;
		str_num = int2str(last_a) + str_num;
	}

	cout<<"The Hex Num = "<<str_num<<endl;
	return 0;
}

string  int2str( int  num)
{
	if (num  ==   0 )
		return   " 0 " ;
	string  str  =   "" ;
	int  num_  =  num  >   0   ?  num :  - 1   *  num;
	while (num_)
	{
		str  =  ( char )(num_  %   10   +   48 )  +  str;
		num_  /=   10 ;
	} 
	if (num  <   0 )
		str  =   " - "   +  str;
	return  str;
}

 

    原文作者:进制转换
    原文地址: https://blog.csdn.net/robertkun/article/details/5381597
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞