c++中如何实现十进制(Dec)与十六进制(Hex)之间的相互转换
1.十进制 -> 十六进制
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
string DecIntToHexStr(long long num)
{
string str;
long long Temp = num / 16;
int left = num % 16;
if (Temp > 0)
str += DecIntToHexStr(Temp);
if (left < 10)
str += (left + '0');
else
str += ('A' + left - 10);
return str;
}
//十进制 -》十六进制
string DecStrToHexStr(string str)
{
long long Dec = 0;
for (int i = 0; i < str.size(); ++i)
Dec = Dec * 10 + str[i] - '0';//得到相应的整数:ASCII码中:字符0的码值是48;
return DecIntToHexStr(Dec);
}
int main()
{
string str_10 = "123";
cout << "十进制:" << atoi(str_10.c_str()) << endl;
string strHex = DecStrToHexStr(str_10);
cout << "十六进制:0x" << strHex.c_str() << endl;
system("pause");
}
结果验证:
2. 十六进制 -> 十进制
#include "stdafx.h"
#include "iostream"
#include "string"
#include <algorithm>
using namespace std;
#define TOLOWER(p) {transform(p.begin(),p.end(),p.begin(),::tolower);}
//十六进制-》十进制
int HexStrToDecStr(string str)
{
int iDec = 0;
TOLOWER(str);
sscanf_s(str.c_str(), "%x", &iDec);
return iDec;
}
int main()
{
string str_16 = "0x7B";
cout <<"十六进制:"<< str_16.c_str() << endl;
int iDec = HexStrToDecStr(str_16);
cout << "十进制:" << iDec << endl;
system("pause");
}
结果验证: