由十进制转换为十六进制字符串(两种方法)
程序员文章站
2024-03-17 13:21:28
...
#include <iostream>
#include<string>
using namespace std;
char tochar(int n)
{
switch(n)
{
case 10:
return 'a';break;
case 11:
return 'b';break;
case 12:
return 'c';break;
case 13:
return 'd';break;
case 14:
return 'e';break;
case 15:
return 'f';break;
default:
return '0'+n;
}
}
string inttohex(int n)
{
string temp="",temp2="";
int index=16;
while(n>0)
{
temp+=tochar(n%index);
n=n/index;
}
for(int i=temp.size()-1;i>=0;--i)
temp2+=temp.at(i);
return temp2;
}
int main()
{
int n;
string res;
while(cin>>n)
{
cout<<"One way:";
cout<<hex<<n<<endl;
res=inttohex(n);
cout<<"Another way:";
cout<<res<<endl;
}
return 0;
}
第二种方法适用性更广,因为在转换的过程中可以得到字符串值,第一种只是利用了设置的输出属性