itoa 和_itoa_s


1 itoa, 將整數轉換為字符串。

char *  itoa ( int value, char * buffer, int radix );

 

它包含三個參數:

value, 是要轉換的數字;

buffer, 是存放轉換結果的字符串;

radix, 是轉換所用的基數,2-36。如,2:二進制,10:十進制,16:十六進制


擴展:
ltoa() 將長整型值轉換為字符串
ultoa() 將無符號長整型值轉換為字符串

 

Example:

#include <stdio.h>
#include <stdlib.h>

int _tmain(int argc, _TCHAR* argv[])
{
    int n;
    char buffer[33];
    printf("Enter a number:");
    scanf("%d",&n);
    itoa(n,buffer,10);
    printf("decimal: %s\n", buffer);

    itoa(n,buffer,16);
    printf("hexadecimal: %s\n", buffer);

    itoa(n,buffer,2);
    printf("binary: %s\n",buffer);
    
return 0;
}
View Code

Output:

Enter a number:6666
decimal: 6666
hexadecimal: 1a0a
binary: 1101000001010
Output

有關 itoa 的詳細介紹,請參照 itoa : Convert integer to string.

 

2_itoa_s, 是 itoa 的安全版本,除了參數和返回值不同,兩個函數的行為是相同的,都是將整數轉換為字符串。

errno_t _itoa_s(int value, char *buffer, size_t sizeInCharacters, int radix);

 

_itoa_s 比 itoa 多出一個參數:

 value, 是要轉換的數字;

buffer, 是存放轉換結果的字符串;

sizeInCharacters, 存放轉換結果的字符串長度

radix, 是轉換所用的基數,2-36。如,2:二進制,10:十進制,16:十六進制

 

Example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int _tmain(int argc, _TCHAR* argv[])
{
    char buffer[65];
    int r;
    for( r=10; r>=2; --r )
    {
       _itoa_s( -1, buffer, 65, r );
       printf( "base %d: %s (%d chars)\n", r, buffer, strnlen(buffer, _countof(buffer)) );
    }
    
    return 0;
}
View Code

Output:

base 10: -1 (2 chars)
base 9: 12068657453 (11 chars)
base 8: 37777777777 (11 chars)
base 7: 211301422353 (12 chars)
base 6: 1550104015503 (13 chars)
base 5: 32244002423140 (14 chars)
base 4: 3333333333333333 (16 chars)
base 3: 102002022201221111210 (21 chars)
base 2: 11111111111111111111111111111111 (32 chars)
Output

有關 _itoa_s 的詳細介紹,請參照_itoa_s, _i64toa_s, _ui64toa_s, _itow_s, _i64tow_s, _ui64tow_s


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM