C语言提供了几个标准库函数,可以将任意类型(整型、长整型、浮点型等)的数字转换为字符串。以下是用itoa()函数将整数转 换为字符串的一个例子:
atoi 把字符串转换成整型数
itoa 把一整数转换为字符串
- #include "stdio.h"
- #include "ctype.h"
- #include "stdlib.h"
-
-
-
-
-
- int my_atoi(char s[])
- {
- int i,n,sign;
-
- for(i=0;isspace(s[i]);i++);
-
- sign=(s[i]=='-')?-1:1;
- if(s[i]=='+'||s[i]==' -')
- i++;
- for(n=0;isdigit(s[i]);i++)
- n=10*n+(s[i]-'0');
- return sign*n;
- }
-
-
-
-
-
- void my_itoa(int n,char s[])
- {
- int i,j,sign;
-
- if((sign=n)<0)
- n=-n;
- i=0;
- do{
- s[i++]=n%10+'0';
- }while((n/=10)>0);
-
- if(sign<0)
- s[i++]='-';
- s[i]='\0';
- for(j=i-1;j>=0;j--)
- printf("%c",s[j]);
- }
-
-
- void main()
- {
- int n;
- char str[100];
- my_itoa(-123,str);
- printf("\n");
- printf("%d\n",my_atoi("123"));
- system("pause");
- }
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);
- 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));
- printf("%d\n",n);
- system("pause");
- return 0;
- }
itoa()函数的扩展:
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;
- }
http://blog.csdn.net/hackbuteer1/article/details/6666959