Linux C编程下没有 itoa()函数的问题

时间: 2023-07-10 admin IT培训

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就是转换后的字符串值