下面是一個圖例表示轉換過程使用的函數
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);
只是簡單寫了一下,沒有考慮效率問題。