1. 程式人生 > >16進位制CString與int相互轉換

16進位制CString與int相互轉換

以下為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;
}