count = 0; /* allocate INTSIZE plus 2 bytes (sign and NULL) */ string = (char *) malloc(INTSIZE + 2); /*--------------------------------------------------------------------+ if (sign < 0) /* add '-' when sign is negative */ *temp-- = '/0'; /* ensure null terminated and point */ /*--------------------------------------------------------------------+ return(string);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 */
if ((sign = value) < 0) /* assign value to sign, if negative */
{ /* keep track and invert value */
value = -value;
count++; /* increment count */
}
temp = (char *) malloc(INTSIZE + 2);
if (temp == NULL)
{
return(NULL);
}
memset(temp,'/0', 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);
*temp++ = '-';
/* 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));
}
}
如何实现 itoa
最新推荐文章于 2024-09-10 06:15:00 发布
本文介绍了一种在C语言中将整数转换为字符串的方法。通过定义一个名为itoa的函数来实现这一过程,该函数接收一个整数值作为输入,并返回对应的字符串表示形式。文章详细介绍了函数内部的工作原理,包括处理负数情况、内存分配、字符串反转等关键步骤。

1345

被折叠的 条评论
为什么被折叠?



