十进制转十六进制 代码

  • Post author:
  • Post category:其他


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;
}



版权声明:本文为robertkun原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。