VC++中2进制,10进制,16进制相互转换

下面是一个图例表示转换过程使用的函数

  BinToDec CString::Format
  2 --------------------------> 10 ---------------------------> 16
  2 <-------------------------- 10 <--------------------------- 16
  DecToBin strtoul 

  1. 2 进制 -----> 10 进制

  CString BinToDec(CString strBin)

  {

  CString strDec;

  long nDec = 0, nLen;

  int i, j, k;

  nLen = strBin.GetLength();

  for (i=0; i<nLen; i++)

  {

  if ( strBin[nLen-i-1] == '0' )

  continue;

  else

  {

  k = 1;

  for(j=0; j<i; j++)

  k = k * 2;

  nDec += k;

  }

  }

  strDec.Format("%ld", nDec);

  return strDec;

  }

  2. 10 进制 -----> 2 进制

  CString DecToBin(CString strDec)

  {

  int nDec = atoi(strDec);

  int nYushu, nShang;

  CString strBin = _T(""), strTemp;

  TCHAR buf[2];

  BOOL bContinue = TRUE;

  while ( bContinue )

  {

  nYushu = nDec % 2;

  nShang = nDec / 2;

  sprintf(buf, "%d", nYushu);

  strTemp = strBin;

  strBin.Format("%s%s", buf, strTemp);

  nDec = nShang;

  if ( nShang == 0 )

  bContinue = FALSE;

  }

  int nTemp = strBin.GetLength()%4;

  switch(nTemp)

  {

  case 1:

  strTemp.Format(_T("000%s"), strBin);

  strBin = strTemp;

  break;

  case 2:

  strTemp.Format(_T("00%s"), strBin);

  strBin = strTemp;

  break;

  case 3:

  strTemp.Format(_T("0%s"), strBin);

  strBin = strTemp;

  break;

  default:

  break;

  }

  return strBin;

  }

  3. 2进制 -----> 16进制

  2进制先转换为10进制,再转换为16进制

  CString strDec, strBin, strHex;

  strBin = _T("1110");

  strDec = BinToDec(strBin);

  int nDec;

  nDec = atol(strDec);

  strHex.Format(_T("%x"), nDec);

  4. 10 进制 -----> 16 进制

  int nDec = 10;

  CString str;

  str.Fomat(_T("%x"), nDec);

  5. 16 进制 -----> 10 进制

  CString strDec, strHex;

  strHex = _T("af");

  DWORD dwHex = strtoul(strHex, NULL, 16);

  strDec.Format(_T("%ld"), dwHex);

  6. 16 进制 -----> 2 进制

  16进制先转换为10进制,再转换为2进制

  CString strDec, strBin, strHex;

  strHex = _T("af");

  DWORD dwHex = strtoul(strHex, NULL, 16);

  strDec.Format(_T("%ld"), dwHex);

  strBin = DecToBin(strDec);

posted @ 2013-01-10 23:56  _**  阅读(672)  评论(0编辑  收藏  举报