At the invitation of a netizen, I wrote a numeric conversion function. If you have any shortcomings, click it.
# Include <stdio. h>
/*
* Function: int convert (INT num, char * STR, unsigned int Radix)
* Function: convert a decimal integer to 2 ~ 36 (excluding 10) hexadecimal number
* Parameter: num decimal integer
* String buffer after STR conversion. Suppose the buffer is large enough.
* Radix Base
* Return value: 1 is returned for successful conversion. Otherwise, 0 is returned.
*/
Int Convert ( Int Num, Char * STR, unsigned Int Radix)
{
Char Num_char [] = " 0123456789 abcdefghijklmnopqrstuvwxyz " ;
If (Radix < 2 | Radix> 36 | Radix = 10 )
Return 0 ;
If (Num < 0 ){
* STR ++ = ' - ' ;
Num =-num;
}
/*
* Convert a decimal integer to radix.
*/
Char* P = STR;
While(Num ){
* P ++ = num_char [num % Radix];
Num/= Radix;
}
* P -- ='\ 0';
/*
* Because the converted numeric string is in reverse order,
* The followingCodeIs to reverse the string
*/
CharCh;
While(STR <p ){
Ch = * STR;
* STR ++ = * P;
* P -- = CH;
}
Return 1;
}
IntMain (IntArgc,Char* Argv [])
{
CharSTR [100] = {0};
Convert (123456, STR,2);//Convert to binary
Printf ("% S \ n", STR );
Convert (123456, STR,8);//Convert to octal
Printf ("% S \ n", STR );
Convert (123456, STR,16);//Convert to hexadecimal
Printf ("% S \ n", STR );
Convert (-123456, STR,20);//Convert to decimal
Printf ("% S \ n", STR );
Convert (123456, STR,36);//Convert to 36 hexadecimal
Printf ("% S \ n", STR );
Return 0;
}