Convert a numeric string to an integer

Source: Internet
Author: User

Question: compile a C function that converts a given string to an integer.

[This program is compiled in Dev C ++ 4.9.9.2]

The following program only considers the decimal string.

Int strtoint (char * Str)

{

Int value = 0;

Int Sign = 1;

If (* STR = '-')

{

Sign =-1;

STR ++;

}

While (* Str)

{

Value = value * 10 + * str-'0 ';

STR ++;

}

Return sign * value;

}

Int main ()

{

Printf ("number = % d/N", strtoint ("1234567 "));

Printf ("number = % d/N", strtos ("-1234567 "));

Printf ("number = % d/N", strtoint ("2147483647 "));

Printf ("number = % d/N", strtos ("-2147483647 "));

System ("pause ");

Return 0;

}

The following program considers octal, decimal, and hexadecimal strings.

Int strtoint (char * Str)

{

Int value = 0;

Int Sign = 1;

Int Radix;

 

If (* STR = '-')

{

Sign =-1;

STR ++;

}

If (* STR = '0' & (* (STR + 1) = 'X' | * (STR + 1) = 'X '))

{

Radix = 16;

STR + = 2;

}

Else if (* STR = '0 ')

{

Radix = 8;

STR ++;

}

Else

Radix = 10;

While (* Str)

{

If (Radix = 16)

{

If (* STR> = '0' & * STR <= '9 ')

Value = value * Radix + * str-'0 ';

Else

Value = value * Radix + (* STR | 0x20)-'A' + 10;

}

Else

Value = value * Radix + * str-'0 ';

STR ++;

}

Return sign * value;

}

Int main ()

{

Printf ("decimal string translation! /N ");

Printf ("/" 1234567/"= % d/N", strtoint ("1234567 "));

Printf ("/"-1234567/"= % d/N", strtoint ("-1234567 "));

Printf ("/" 2147483647/"= % d/N", strtoint ("2147483647 "));

Printf ("/"-2147483647/"= % d/N", strtoint ("-2147483647 "));

Printf ("/nhex string translation! /N ");

Printf ("/" 0x200/"= % d/N", strtoint ("0x200 "));

Printf ("/"-0x200/"= % d/N", strtoint ("-0x200 "));

Printf ("/" 0x7fffffff/"= % d/N", strtoint ("0x7fffffff "));

Printf ("/"-0x7fffffff/"= % d/N", strtoint ("-0x7fffffff "));

Printf ("/noctal string translation! /N ");

Printf ("/" 0123/"= % d/N", strtoint ("0123 "));

Printf ("/"-0123/"= % d/N", strtoint ("-0123 "));

System ("pause ");

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.