atoi 与 itoa的详解和实现源代码

2024-04-04 14:58

本文主要是介绍atoi 与 itoa的详解和实现源代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一)C语言库函数名: int atoi(const char *nptr);

①函数解释

功 能: 把字符串转换成整型数.
名字来源:array to integer 的缩写.
函数说明: 参数nptr字符串,如果第一个非空格字符不存在或者不是数字也不是正负号则返回零,否则开始做类型转换,之后检测到非数字(包括结束符 \0) 字符时停止转换,返回整型数。
头文件: #include <stdlib.h>

②使用例子:

#include <stdio.h>
#include <stdlib.h>
int main(void)
{int n;char *str = "12345.67";n = atoi(str);printf("string = %s integer = %d\n", str, n);char a[] = "-100" ;char b[] = "123" ;int c = atoi( a ) + atoi( b ) ;printf("c = %d\n", c) ;return 0;
}
//执行结果
//string = 12345.67 integer = 12345
//c = 23

③实现atoi()和atol ()的源代码(32位机器):

Nginx实现

ngx_int_t
ngx_atoi(u_char *line, size_t n)
{ngx_int_t  value;if (n == 0) {return NGX_ERROR;}for (value = 0; n--; line++) {if (*line < '0' || *line > '9') {return NGX_ERROR;}value = value * 10 + (*line - '0');}if (value < 0) {return NGX_ERROR;} else {return value;}}
#include <cruntime.h>
#include <stdlib.h>
#include <ctype.h>
/***
*long atol(char *nptr) - Convert string to long
*
*Purpose:
* Converts ASCII string pointed to by nptr to binary.
* Overflow is not detected.
*
*Entry:
* nptr = ptr to string to convert
*
*Exit:
* return long int value of the string
*
*Exceptions:
* None - overflow is not detected.
*
*******************************************************************************/
long __cdecl atol(const char *nptr)
{int c; /* current char */long total; /* current total */int sign; /* if ''-'', then negative, otherwise positive *//* skip whitespace */while ( isspace((int)(unsigned char)*nptr) )++nptr;c = (int)(unsigned char)*nptr++;sign = c; /* save sign indication */if (c == '-' || c == '+')c = (int)(unsigned char)*nptr++; /* skip sign */total = 0;while (isdigit(c)) {total = 10 * total + (c - '0'); /* accumulate digit */c = (int)(unsigned char)*nptr++; /* get next char */}if (sign == '-')return -total;elsereturn total; /* return result, negated if necessary */
}
int __cdecl atoi(const char *nptr)
{return (int)atol(nptr);
}

说明:atol()只转换ASCII的数字,所以每次取下一字符时指针移动8位,传入的指针用const char有一部分原因是习惯问题;转换为unsigned char是因为ASCII字符是从0x0~0xff而没有负的,转换为int防止编译器的不同,自动转换的结果不同;、

自己实现的isdigit()函数:

inline int isdigit(unsigned char ch)
{const int m_nData = (int)(unsigned char)(ch - '0');if((m_nData >= 0) && (m_nData <=9))return m_nData;elsereturn 0;
}

//溢出的现象:

// overflow  if(total > std::numeric_limits<int>::max()){total = 0;break;}

Microsoft:

isspace(int x)    
{    if(x==' '||x=='/t'||x=='/n'||x=='/f'||x=='/b'||x=='/r')    return 1;    else     return 0;    
}    isdigit(int x)    
{    if(x<='9'&&x>='0')             return 1;     else     return 0;    
}   

在64位机器上的实现:

#ifndef _NO_INT64
__int64 __cdecl _atoi64(const char *nptr)
{int c;__int64 total;int sign;while ( isspace((int)(unsigned char)*nptr) )++nptr;c = (int)(unsigned char)*nptr++;sign = c;if (c == ''-'' || c == ''+'')c = (int)(unsigned char)*nptr++;total = 0;while (isdigit(c)) {total = 10 * total + (c - ''0'');c = (int)(unsigned char)*nptr++;}if (sign == ''-'')return -total;elsereturn total;
}
#endif

二)C语言库函数名:char *itoa(int value, char *string, int radix);

①函数解释:

参数说明:int value 被转换的整数,char *string 转换后储存的字符数组,int radix 转换进制数,如2,8,10,16 进制等。

返回值:指向string这个字符串的指针
②使用例子:

#include <stdlib.h>
#include <stdio.h>
int main(void)
{int number = 12345;char string[25];itoa(number, string, 10); //按十进制转换printf("integer = %d string = %s\n", number, string);itoa(number, string, 16); //按16进制转换printf("integer = %d string = %s\n", number, string);return 0;
}
//输出结果:
//integer = 12345 string = 12345 --说明12345的十进制表示就是12345
//integer = 12345 string = 3039 ——说明12345的十六进制表示是0x3039

③实现itoa和ltoa ()的源代码:

char* itoa(int value, char* string, int radix)
{char tmp[33];char* tp = tmp;int i;unsigned v;int sign;char* sp;if (radix > 36 || radix <= 1){//__set_errno(EDOM);return 0;}sign = (radix == 10 && value < 0);if (sign)v = -value;elsev = (unsigned)value;while (v || tp == tmp){i = v % radix;v = v / radix;if (i < 10)*tp++ = i + '0';else*tp++ = i + 'a' - 10;}if (string == 0)string = (char*)malloc((tp-tmp)+sign+1);sp = string;if (sign)*sp++ = '-';while (tp > tmp)*sp++ = *--tp;*sp = '\0';return string;
} 

补充的部分:

itoa并不是一个标准的C函数,它是Windows特有的,如果要写跨平台的程序,请用sprintf.

char str[255];
sprintf(str, "%x", 100); //将100转为16进制表示的字符串
另外常见的相关函数有:

atol();//实现从字符串转换到长整型
ltoa(); //将长整型值转换为字符串
ultoa();// 将无符号长整型值转换为字符串



这篇关于atoi 与 itoa的详解和实现源代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/876090

相关文章

Java注解之超越Javadoc的元数据利器详解

《Java注解之超越Javadoc的元数据利器详解》本文将深入探讨Java注解的定义、类型、内置注解、自定义注解、保留策略、实际应用场景及最佳实践,无论是初学者还是资深开发者,都能通过本文了解如何利用... 目录什么是注解?注解的类型内置注编程解自定义注解注解的保留策略实际用例最佳实践总结在 Java 编程

MySQL数据库约束深入详解

《MySQL数据库约束深入详解》:本文主要介绍MySQL数据库约束,在MySQL数据库中,约束是用来限制进入表中的数据类型的一种技术,通过使用约束,可以确保数据的准确性、完整性和可靠性,需要的朋友... 目录一、数据库约束的概念二、约束类型三、NOT NULL 非空约束四、DEFAULT 默认值约束五、UN

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

MySQL中的分组和多表连接详解

《MySQL中的分组和多表连接详解》:本文主要介绍MySQL中的分组和多表连接的相关操作,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录mysql中的分组和多表连接一、MySQL的分组(group javascriptby )二、多表连接(表连接会产生大量的数据垃圾)MySQL中的

Java 实用工具类Spring 的 AnnotationUtils详解

《Java实用工具类Spring的AnnotationUtils详解》Spring框架提供了一个强大的注解工具类org.springframework.core.annotation.Annot... 目录前言一、AnnotationUtils 的常用方法二、常见应用场景三、与 JDK 原生注解 API 的

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

redis中使用lua脚本的原理与基本使用详解

《redis中使用lua脚本的原理与基本使用详解》在Redis中使用Lua脚本可以实现原子性操作、减少网络开销以及提高执行效率,下面小编就来和大家详细介绍一下在redis中使用lua脚本的原理... 目录Redis 执行 Lua 脚本的原理基本使用方法使用EVAL命令执行 Lua 脚本使用EVALSHA命令

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B