博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何实现 itoa
阅读量:2221 次
发布时间:2019-05-08

本文共 1729 字,大约阅读时间需要 5 分钟。

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);

}

转载地址:http://ruifb.baihongyu.com/

你可能感兴趣的文章
后端技术杂谈9:先搞懂Docker核心概念吧
查看>>
后端技术杂谈10:Docker 核心技术与实现原理
查看>>
夯实Java基础系列2:Java自动拆装箱里隐藏的秘密
查看>>
夯实Java基础系列1:Java面向对象三大特性(基础篇)
查看>>
夯实Java基础系列3:一文搞懂String常见面试题,从基础到实战,更有原理分析和源码解析!
查看>>
夯实Java基础系列4:一文了解final关键字的特性、使用方法,以及实现原理
查看>>
Java 未来行情到底如何,来看看各界人士是怎么说的
查看>>
IntelliJ 平台 2020 年路线图
查看>>
走进JavaWeb技术世界8:浅析Tomcat9请求处理流程与启动部署过程
查看>>
微软宣布加入 OpenJDK,打不过就改变 Java 未来!
查看>>
MyBatis动态SQL(认真看看, 以后写SQL就爽多了)
查看>>
为什么强烈推荐 Java 程序员使用 Google Guava 编程!
查看>>
先搞清楚这些问题,简历上再写你熟悉Java!
查看>>
【数据库】关系数据库和非关系数据库的优缺点
查看>>
【数据结构】动态顺序表
查看>>
Markdown的基础使用
查看>>
Linux基础命令
查看>>
【C语言】交换两个数值的三种方法
查看>>
【数据结构】栈的简单理解以及对栈的基本操作
查看>>
【数据结构】简单不带环迷宫的实现(用栈实现)
查看>>