Itoa functions in Linux

Source: Internet
Author: User

Linux requires the itoa function. Next I will provide a cross-platform itoa function.

// Return the length of result string. support only 10 radix for easy use and better performance

Int my_itoa (int val, char * buf)

{

Const int radix = 10;

Char * p;

Int a; // every digit

Int len;

Char * B; // start of the digit char

Char temp;

P = buf;

If (val <0)

{

* P ++ = '-';

Val = 0-val;

}

B = p;

Do

{

A = val % radix;

Val/= radix;

* P ++ = a + '0 ';

} While (val> 0 );

Len = (int) (p-buf );

* P -- = 0;

// Swap

Do

{

Temp = * p;

* P = * B;

* B = temp;

-- P;

+ + B;

} While (B <p );

Return len;

}

This function returns the length of the string, which is useful in some cases.

I tested it. This function is about 20% faster than the itoa provided by MFC.

(Because if (a> 9) does not need to be determined in the circular body, it is faster ).

2010/1/8 Ultimate Edition:

// Return the length of result string. support only 10 radix for easy use and better performance

Int my_itoa (int val, char * buf)

{

Const unsigned int radix = 10;

Char * p;

Unsigned int a; // every digit

Int len;

Char * B; // start of the digit char

Char temp;

Unsigned int u;

P = buf;

If (val <0)

{

* P ++ = '-';

Val = 0-val;

}

U = (unsigned int) val;

B = p;

Do

{

A = u % radix;

U/= radix;

* P ++ = a + '0 ';

} While (u> 0 );

Len = (int) (p-buf );

* P -- = 0;

// Swap

Do

{

Temp = * p;

* P = * B;

* B = temp;

-- P;

+ + B;

} While (B <p );

Return len;

}

Improvement: Change the division operation from a signed integer to an unsigned integer. The typical speed is increased from about 240 milliseconds to about 180 milliseconds. In comparison, it takes about 320 ms for the itoa provided by MFC.

(The Division of unsigned integers on x86 machines is faster, with different assembly commands)

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.