Deeply understand the usage of atoi of and itoa of functions

  • 2020-04-01 23:44:52
  • OfStack

The prototype of the itoa() function is: char *itoa(int value, char *string,int radix);
The itoa() function takes three arguments: the first argument is the number to be converted, the second argument is the target string to write the result of the conversion, and the third argument is the cardinality used to convert the number. In the example, the conversion base is 10. 10: decimal; 2: binary...
Itoa is not a standard C function. It is windows-specific. If you are writing cross-platform programs, use sprintf.
Sprintf is an extension of the Windows platform. The standard library has sprintf, which is more powerful than this one. The usage is similar to printf:
Char STR [255].
Sprintf (STR, "% x", 100); // converts 100 to a hexadecimal string.
Here is a decimal to octal method:

#include "stdio.h"
#include "stdlib.h"
int main(void)
{
 int num = 10;
 char str[100];
 itoa(num, str, 8);      //Converts the integer 10 to octal and stores it in an array of STR characters
 printf("%sn", str);
 system("pause");
 return 0;
}

Here is a decimal to binary method:

#include "stdio.h"
#include "stdlib.h"
int main(void)
{
 int num = 15;
 char str[100];
 int n = atoi(itoa(num, str, 2));   //Num is converted to a binary string and then to an integer
 printf("%dn",n);
 system("pause");
 return 0;
}

Extension of itoa() function:

char *_itoa( int value, char *string, int radix );
char *_i64toa( __int64 value, char *string, int radix );
char * _ui64toa( unsigned _int64 value, char *string, int radix );
wchar_t * _itow( int value, wchar_t *string, int radix );
wchar_t * _i64tow( __int64 value, wchar_t *string, int radix );
wchar_t * _ui64tow( unsigned __int64 value, wchar_t *string, int radix );

The program code is as follows:

#include "stdio.h"
#include "stdlib.h"
int main(void)
{
 char buffer[20];
 int i = 3445;
 long l = -344115L;
 unsigned long ul = 1234567890UL;
 _itoa( i, buffer, 10 );
 printf( "String of integer %d (radix 10): %sn", i, buffer );
 _itoa( i, buffer, 16 );
 printf( "String of integer %d (radix 16): 0x%sn", i, buffer );
 _itoa( i, buffer, 2 );
 printf( "String of integer %d (radix 2): %sn", i, buffer );
 _ltoa( l, buffer, 16 );
 printf( "String of long int %ld (radix 16): 0x%sn", l,buffer );
 _ultoa( ul, buffer, 16 );
 printf( "String of unsigned long %lu (radix 16): 0x%sn", ul,buffer );
 system("pause");
 return 0;
}


Related articles: