Convert the decimal integer to 2 ~ 36 (excluding 10) hexadecimal number

Source: Internet
Author: User

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;

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.