实现itoa函数的源代码

char *my_itoa(int num,char *str,int radix)

{
  const char table[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  char *ptr = str;
  bool negative = false;
  if(num == 0){   //num=0
  *ptr++='0';
  *ptr='\0';                // don`t forget the end of the string is '\0'!!!!!!!!!
  return str;
  }
  if(num<0){               //if num is negative ,the add '-'and change num to positive
  *ptr++='-';
  num*=-1;
  negative = true;
  }
  while(num){
  *ptr++ = table[num%radix];
  num/=radix;
  }
  *ptr = '\0';            //if num is negative ,the add '-'and change num to positive
  // in the below, we have to converse the string
  char *start =(negative?str+1:str); //now start points the head of the string
  ptr--;                           //now prt points the end of the string
  while(start<ptr){
  char temp = *start;
  *start = *ptr;
  *ptr = temp;
  start++;
  ptr--;
  }
  return str;
  }

 

  1. /* 实现itoa函数的源代码 */   
  2. char *myitoa(int num,char *str,int radix)   
  3. {    
  4.     /* 索引表 */   
  5.     char index[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";   
  6.     unsigned unum; /* 中间变量 */   
  7.     int i=0,j,k;   
  8.     /* 确定unum的值 */   
  9.     if(radix==10&&num<0) /* 十进制负数 */   
  10.     {   
  11.         unum=(unsigned)-num;   
  12.         str[i++]='-';   
  13.     }   
  14.     else unum=(unsigned)num; /* 其他情况 */   
  15.     /* 逆序 */   
  16.     do    
  17.     {   
  18.         str[i++]=index[unum%(unsigned)radix];   
  19.         unum/=radix;   
  20.     }while(unum);   
  21.     str[i]='\0';   
  22.     /* 转换 */   
  23.     if(str[0]=='-') k=1; /* 十进制负数 */   
  24.     else k=0;   
  25.     /* 将原来的“/2”改为“/2.0”,保证当num在16~255之间,radix等于16时,也能得到正确结果 */   
  26.     char temp;   
  27.     for(j=k;j<=(i-k-1)/2.0;j++)   
  28.     {   
  29.         temp=str[j];   
  30.         str[j]=str[i-j-1];   
  31.         str[i-j-1]=temp;   
  32.     }   
  33.     return str;   
  34. }   

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值