In VC ++, there are two hexadecimal, 10 hexadecimal, and 16 hexadecimal conversions.
Author: lixiaosan
Date: 04/14/2006
The following is a legend indicating the function used in the conversion process.
Bintodec cstring: Format
2 --------------------------> 10 -----------------------------> 16
2 <-------------------------- 10 <--------------------------- 16
Dectobin strtoul
1. 2 hexadecimal -----> 10 hexadecimal
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 hexadecimal -----> 2 hexadecimal
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 hexadecimal -----> 16 hexadecimal
Binary is first converted to hexadecimal and then to hexadecimal.
Cstring strdec, strbin, strhex;
Strbin = _ T ("1110 ");
Strdec = bintodec (strbin );
Int ndec;
Ndec = atol (strdec );
Strhex. Format (_ T ("% x"), ndec );
4. 10 hexadecimal -----> 16 hexadecimal
Int ndec = 10;
Cstring STR;
Str. fomat (_ T ("% x"), ndec );
5. hexadecimal -----> 10 hexadecimal
Cstring strdec, strhex;
Strhex = _ T ("af ");
DWORD dwhex = strtoul (strhex, null, 16 );
Strdec. Format (_ T ("% lD"), dwhex );
6. hexadecimal -----> binary
Hexadecimal is first converted to hexadecimal and then to binary.
Cstring strdec, strbin, strhex;
Strhex = _ T ("af ");
DWORD dwhex = strtoul (strhex, null, 16 );
Strdec. Format (_ T ("% lD"), dwhex );
Strbin = dectobin (strdec );
I just wrote it briefly without considering the efficiency issue.