1. 程式人生 > >Linux C程式設計下沒有 itoa()函式的問題

Linux C程式設計下沒有 itoa()函式的問題

用ubuntu linux c程式設計,發現Linux核心中只有atoi()函式,被包含在stdlib.h標頭檔案中,而沒有itoa()函式,網上查了有一個實現了itoa()函式的程式碼

void   itoa   (   unsigned   long   val,   char   *buf,   unsigned   radix   )   
{   
                char   *p;                                 /*   pointer   to   traverse   string   */   
                char   *firstdig;                   /*   pointer   to   first   digit   */   
                char   temp;                             /*   temp   char   */   
                unsigned   digval;                 /*   value   of   digit   */   

                p   =   buf;   
                firstdig   =   p;                       /*   save   pointer   to   first   digit   */   

                do   {   
                        digval   =   (unsigned)   (val   %   radix);   
                        val   /=   radix;               /*   get   next   digit   */   

                        /*   convert   to   ascii   and   store   */   
                        if   (digval   >   9)   
                                *p++   =   (char   )   (digval   -   10   +   'a ');     /*   a   letter   */   
                        else   
                                *p++   =   (char   )   (digval   +   '0 ');               /*   a   digit   */   
                }   while   (val   >   0);   

                /*   We   now   have   the   digit   of   the   number   in   the   buffer,   but   in   reverse   
                      order.     Thus   we   reverse   them   now.   */   

                *p--   =   '\0 ';                         /*   terminate   string;   p   points   to   last   digit   */   

                do   {   
                        temp   =   *p;   
                        *p   =   *firstdig;   
                        *firstdig   =   temp;       /*   swap   *p   and   *firstdig   */   
                        --p;   
                        ++firstdig;                   /*   advance   to   next   two   digits   */   
                }   while   (firstdig   <   p);   /*   repeat   until   halfway   */   
}

不過,測試時發現這個實現將數字轉換成了亂碼。比較簡潔的方法是用sprintf()函式代替。具體程式碼如下:

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

  int main()
  {
      int number = 429496729;
       char string[25];
       sprintf(string, "%d", number);

       printf("integer = %d string = %s\n", number, string);
       return 0;
  }

此時string就是轉換後的字串值