1. 程式人生 > >atoi 與 itoa 函式用法

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 = 10char 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 = 15char str[100]; int n = atoi(itoa(num, str, 2
));   //先把num轉換為二進位制的字串,再把該字串轉換為整數 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 = 3445long l = -344115Lunsigned 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;}