atoi 和 itoa的实现
来源:互联网 发布:喜马拉雅网络无法连接 编辑:程序博客网 时间:2024/06/05 07:53
atoi 和 itoa的实现
转载:http://www.cnblogs.com/cobbliu/archive/2012/08/25/2656176.html
atoi 和 itoa是面试笔试经常要考到的题目,下面两份代码是用C语言实现的atoi和itoa:
1, atoi
原型: int atoi(const char *nptr);
函数说明: 参数nptr字符串,如果第一个非空格字符不存在或者不是数字也不是正负号则返回零,否则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。
#include <stdio.h>#include <assert.h>static int atoi(const char* str){ int result = 0; int sign = 0; assert(str != NULL); // proc whitespace characters while (*str==' ' || *str=='\t' || *str=='\n') ++str; // proc sign character if (*str=='-') { sign = 1; ++str; } else if (*str=='+') { ++str; } // proc numbers while (*str>='0' && *str<='9') { result = result*10 + *str - '0'; ++str; } // return result if (sign==1) return -result; else return result;}
2. itoa
char *itoa( int value, char *string,int radix);
原型说明:
value:欲转换的数据。
string:目标字符串的地址。
radix:转换后的进制数,可以是10进制、16进制等
char *itoa(int val, char *buf, unsigned radix){ char *p; char *firstdig; char temp; unsigned digval; p = buf; if(val <0) { *p++ = '-'; val = (unsigned long)(-(long)val); } firstdig = p; do{ digval = (unsigned)(val % radix); val /= radix; if (digval > 9) *p++ = (char)(digval - 10 + 'a'); else *p++ = (char)(digval + '0'); }while(val > 0); *p-- = '\0 '; do{ temp = *p; *p = *firstdig; *firstdig = temp; --p; ++firstdig; }while(firstdig < p); return buf;}
0 0
- atoi和itoa的实现
- atoi和itoa的实现
- atoi 和itoa的实现
- atoi和itoa的实现
- atoi 和 itoa的实现
- atoi和itoa的实现
- atoi 和itoa实现
- atoi 和 itoa实现
- 实现itoa()和atoi()
- atoi() itoa() 的实现
- atoi和itoa的C实现
- atoi()和itoa()的标准源码实现
- atoi()和itoa()的标准源码实现
- atoi和itoa的C++实现
- atoi()和itoa()的标准源码实现
- atoi和itoa函数的实现
- atoi和itoa的编程实现
- atoi和itoa函数的实现方法
- maven编码 gbk 的不可映射字符
- Android Binder设计与实现 – 设计篇
- UIScrollView+UIView无法点击
- Java反射机制之动态加载
- LiDAR数据常用处理软件
- atoi 和 itoa的实现
- 汽车内部清洗具有哪些?
- Paint与Canvas(形状工具本质都是调用画笔工具)
- sendRedirect和getRequestDispatcher().forward()的一些区别
- 我的ROS入门(四):ROS文件系统
- Sonatype nexus 搭建本地私服
- UVA - 11294 Wedding(2-SAT)
- 咕嘟咕嘟,香味冒出来
- 汽车内部清洗的部位有哪些