以下为VC2008下实现代码:
一、int型转16进制CString
CString IntToCStringHex(int algorism)//十六进制转换
{
vector<int> reNum;
CString str;
//倒序输出
do
{
int nTemp = algorism%16;
algorism=algorism/16;
reNum.push_back(nTemp);
}while(algorism);
//注释部分为加0,如有必要可采用
// while(reNum.size() < 4)
// {
// reNum.push_back(0);
// }
//倒序输出
for (int i = reNum.size()-1; i >=0 ; --i)
{
CString strTemp;
if (reNum[i]>=10 && reNum[i]<=15)
{
WCHAR ch = 'A' + reNum[i]-10; //VC2008下用WCHAR,VC6.0应该用char
strTemp = ch;
}
else
{
strTemp.Format(_T("%d"),reNum[i]);
}
str += strTemp;
}
return str;
}
二、16进制CString转int型
int CStringHexToInt(CString str)
{
int nRet = 0;
int count = 1;
for(int i = str.GetLength()-1; i >= 0; --i)
{
int nNum = 0;
char chTest;
chTest = str.GetAt(i); //CString一般没有这种用法,但本程序不会有问题
if (chTest >= '0' && chTest <= '9')
{
nNum = chTest - '0';
}
else if (chTest >= 'Á' && chTest <= 'F')
{
nNum = chTest - 'A' + 10;
}
else if (chTest >= 'a' && chTest <= 'f')
{
nNum = chTest - 'a' + 10;
}
nRet += nNum*count;
count *= 16;
}
return nRet;
}