如何实现 itoa


char *itoa(int value)
{
int count, /* number of characters in string */
i, /* loop control variable */
sign; /* determine if the value is negative */
char *ptr, /* temporary pointer, index into string */
*string, /* return value */
*temp; /* temporary string array */

count = 0;
if ((sign = value) < 0) /* assign value to sign, if negative */
{ /* keep track and invert value */
value = -value;
count++; /* increment count */
}

/* allocate INTSIZE plus 2 bytes (sign and NULL) */
temp = (char *) malloc(INTSIZE + 2);
if (temp == NULL)
{
return(NULL);
}
memset(temp,'/0', INTSIZE + 2);

string = (char *) malloc(INTSIZE + 2);
if (string == NULL)
{
return(NULL);
}
memset(string,'/0', INTSIZE + 2);
ptr = string; /* set temporary ptr to string */

/*--------------------------------------------------------------------+
| NOTE: This process reverses the order of an integer, ie: |
| value = -1234 equates to: char [4321-] |
| Reorder the values using for {} loop below |
+--------------------------------------------------------------------*/
do {
*temp++ = value % 10 + '0'; /* obtain modulus and or with '0' */
count++; /* increment count, track iterations*/
} while (( value /= 10) >0);

if (sign < 0) /* add '-' when sign is negative */
*temp++ = '-';

*temp-- = '/0'; /* ensure null terminated and point */
/* to last char in array */

/*--------------------------------------------------------------------+
| reorder the resulting char *string: |
| temp - points to the last char in the temporary array |
| ptr - points to the first element in the string array |
+--------------------------------------------------------------------*/
for (i = 0; i < count; i++, temp--, ptr++)
{
memcpy(ptr,temp,sizeof(char));
}

return(string);
}

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值