深入理解atoi()与itoa()函数的用法
itoa()函数的原型为: char *itoa( int value, char *string,int radix);
itoa()函数有3个参数:第一个参数是要转换的数字,第二个参数是要写入转换结果的目标字符串,第三个参数是转换数字时所用的基数。在例中,转换基数为10。10:十进制;2:二进制...
itoa并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf。
是Windows平台下扩展的,标准库中有sprintf,功能比这个更强,用法跟printf类似:
char str[255];
sprintf(str, "%x", 100); //将100转为16进制表示的字符串。
下面是一个十进制转八进制的方法:
代码如下:
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int num = 10;
char str[100];
itoa(num, str, 8); //将整数10转换为八进制保存在str字符数组中
printf("%s\n", str);
system("pause");
return 0;
}
#include "stdio.h"
#include "stdlib.h"
int main(void)
{
int num = 15;
char str[100];
int n = atoi(itoa(num, str, 2)); //先把num转换为二进制的字符串,再把该字符串转换为整数
printf("%d\n",n);
system("pause");
return 0;
}
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 );
#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): %s\n", i, buffer );
_itoa( i, buffer, 16 );
printf( "String of integer %d (radix 16): 0x%s\n", i, buffer );
_itoa( i, buffer, 2 );
printf( "String of integer %d (radix 2): %s\n", i, buffer );
_ltoa( l, buffer, 16 );
printf( "String of long int %ld (radix 16): 0x%s\n", l,buffer );
_ultoa( ul, buffer, 16 );
printf( "String of unsigned long %lu (radix 16): 0x%s\n", ul,buffer );
system("pause");
return 0;
}