自己实现c语言itoa函数

In this article, we’ll take a look at implementing the itoa() function in C/C++.

在本文中,我们将介绍如何在C / C ++中实现itoa()函数。

This is a useful utility function which converts an integer into a null-terminated string.

这是一个有用的实用程序函数,它将整数转换为以空值结尾的字符串。

However, it isn’t supported natively by most compilers, as it is not a part of the C standard.

但是,大多数编译器本身都不支持它,因为它不是C标准的一部分。

Therefore, let’s take a look at using this function, by implementing it ourselves!.

因此,让我们来看看如何通过自己实现此功能!

C / C ++中itoa()函数的基本语法 (Basic Syntax of the itoa() function in C/C++)

While this function may be available in some compilers, there is no function as such, in most of them.

尽管此功能在某些编译器中可用,但在大多数编译器中都没有这样的功能。

The itoa() function takes in an integer num, and stores it into buffer. It also has an optional parameter base, which converts it into the appropriate base.

itoa()函数接受一个整数num ,并将其存储到buffer 。 它还具有一个可选的参数base ,它将其转换为适当的基数。

By default, base is set to 10 (decimal base).

默认情况下, base设置为10(十进制基数)。

After populating buffer, it returns a pointer to the first character of buffer, if the conversion is successful. Otherwise, it returns NULL.

填充buffer之后,如果转换成功,它将返回一个指向buffer的第一个字符的指针。 否则,它返回NULL


char* itoa(int num, char* buffer, int base)

Since there isn’t any default itoa() function in most common C compilers, let’s implement it!

由于在大多数常见的C编译器中没有默认的itoa()函数,因此让我们实现它!



在C / C ++中实现itoa()函数 (Implementing the itoa() function in C / C++)

We’ll take a number, and convert it to a string. We’ll consider both positive and negative integers, and see how itoa() handles them.

我们将取一个数字,并将其转换为字符串。 我们将同时考虑正整数和负整数,并查看itoa()如何处理它们。

Although some websites may have implemented itoa() by evaluating the digits from right to left and then reversing the string, we’ll use a different approach. t

尽管某些网站可能已经通过从右到左评估数字然后反转字符串来实现itoa() ,但我们将使用另一种方法。 Ť

We’ll evaluate the digits from left to right, with the help of certain function from the <math.h> library.

<math.h>库中的某些功能的帮助下,我们将从左至右评估数字。

We’ll follow the below procedure:

我们将遵循以下过程:

  • Find the number of digits of num. If num is positive, we know that the number of digits will be floor(log(num, base)) + 1. (Hint: This is pretty easy to derive using logarithms).查找num的位数。 如果num为正数,我们知道位数为floor(log(num, base)) + 1 。 (提示:使用对数很容易得出)。
  • If num is negative, we will only consider the case where base = 10, since we may need to use separate algorithms to evaluate for any base. We need to put the minus sign as the first digit!如果num为负,我们将仅考虑base = 10的情况,因为我们可能需要使用单独的算法来评估任何基数。 我们需要将减号放在第一位!
  • Start from the leftmost (highest) digit of num, and keep adding the value to the buffer.从num的最左(最高)位开始,然后继续将值添加到缓冲区中。

The complete program is shown below. You may be able to understand this better by reading through the code!

完整的程序如下所示。 通过阅读代码,您也许可以更好地理解这一点!


#include <stdio.h>
#include <math.h>
#include <stdlib.h>char* itoa(int num, char* buffer, int base) {int curr = 0;if (num == 0) {// Base casebuffer[curr++] = '0';buffer[curr] = '\0';return buffer;}int num_digits = 0;if (num < 0) {if (base == 10) {num_digits ++;buffer[curr] = '-';curr ++;// Make it positive and finally add the minus signnum *= -1;}else// Unsupported base. Return NULLreturn NULL;}num_digits += (int)floor(log(num) / log(base)) + 1;// Go through the digits one by one// from left to rightwhile (curr < num_digits) {// Get the base value. For example, 10^2 = 1000, for the third digitint base_val = (int) pow(base, num_digits-1-curr);// Get the numerical valueint num_val = num / base_val;char value = num_val + '0';buffer[curr] = value;curr ++;num -= base_val * num_val;}buffer[curr] = '\0';return buffer;
}int main() {int a = 1234;char buffer[256];if (itoa(a, buffer, 10) != NULL) {printf("Input = %d, base = %d, Buffer = %s\n", a, 10, buffer);}int b = -231;if (itoa(b, buffer, 10) != NULL) {printf("Input = %d, base = %d, Buffer = %s\n", b, 10, buffer);}int c = 10;if (itoa(c, buffer, 2) != NULL) {printf("Input = %d, base = %d, Buffer = %s\n", c, 2, buffer);}return 0;
}

Output

输出量


Input = 1234, base = 10, Buffer = 1234
Input = -231, base = 10, Buffer = -231
Input = 10, base = 2, Buffer = 1010

NOTE: If you’re compiling with gcc, use the -lm flag to include the math library.

注意 :如果使用gcc ,请使用-lm标志包括数学库。


gcc -o test.out test.c -lm

Indeed, we were able to get it working. Not only did this work for integers, but only for other bases too!

确实,我们能够使其正常运行。 这不仅适用于整数,还适用于其他基数!



结论 (Conclusion)

Hopefully you were able to get an understanding to converting integers to strings using itoa(), and possibly even implemented one yourself, using this guide!

希望您能够理解使用itoa()将整数转换为字符串的方法,甚至可以使用本指南自己实现!

For similar content, do go through our tutorial section on C programming

对于类似的内容,请阅读我们有关C编程的教程部分



翻译自: https://www.journaldev.com/40684/itoa-function-c-plus-plus

自己实现c语言itoa函数

自己实现c语言itoa函数_在C / C ++中实现itoa()函数相关推荐

  1. matlab中floor函数,floor函数_怎么在excel中使用floor函数

    floor函数即上取整函数,是计算机C语言中的数学函数,与ceil函数相对应.但是它在excel中却是另一种含义,FLOOR函数是向下舍入为最接近指数基数的倍数,下面小编就教你怎么在excel中使用f ...

  2. python中add函数_如何使用python中的add函数?

    之前向大家介绍过python中的求和函数sum函数,numpy中的sum函数,对于数组可以指定维度进行相加.numpy中还有另一种求和运算方法,即add函数.add函数不仅作用于numpy中加法运算, ...

  3. python中index函数_详解python中的index函数用法

    1.函数的创建 def fun(): #定义 print('hellow') #函数的执行代码 retrun 1 #返回值 fun() #执行函数 2.函数的参数 普通参数 :要按照顺序输入参数 de ...

  4. 原生js已载入就执行函数_手写CommonJS 中的 require函数

    前言 来自于圣松大佬的文章<手写CommonJS 中的 require函数> 什么是 CommonJS ? node.js 的应用采用的commonjs模块规范. 每一个文件就是一个模块, ...

  5. mounted钩子函数_怎样实现Vue中mounted钩子函数获取节点高度

    这次给大家带来怎样实现Vue中mounted钩子函数获取节点高度,实现Vue中mounted钩子函数获取节点高度的注意事项有哪些,下面就是实战案例,一起来看一下. 遇到的问题 最近在开发一个Vue的项 ...

  6. python grid函数_详解numpy中的meshgrid函数用法

    numpy中的meshgrid函数的使用 numpy官方文档meshgrid函数帮助文档https://docs.scipy.org/doc/numpy/reference/generated/num ...

  7. python hasattr函数_浅谈python中的getattr函数 hasattr函数

    hasattr(object, name) 作用:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的). 示例: & ...

  8. python numpy sum函数_如何使用Python中的sum函数?

    之前小编向大家介绍过python中的sum函数(https://www.py.cn/jishu/jichu/22025.html).在python中sunm函数使用分为两种情况,一种是python自带 ...

  9. python中从小到大排序的函数_深入理解Python中的排序函数

    由于 Python2 和 Python3 中的排序函数略有区别,本文以Python3为主. Python 中的排序函数有 sort , sorted 等,这些适用于哪些排序,具体怎么用,今天就来说一说 ...

最新文章

  1. python文本分类评价指标 top1如何计算_python – Keras:如何计算多标签分类的准确......
  2. [推荐] 创业者要留意优先清算权
  3. zabbix 安装使用
  4. linux头文件怎么编译,microsoft编译器怎么使用Linux头文件
  5. (int),Int32.Parse,Convert.ToInt3…
  6. northstar机器人编程_NorthSTAR图形化机器人开发环境
  7. sncr脱硝技术流程图_脱硝技术介绍(SCR和SNCR)
  8. Tiny6410 U-boot移植
  9. 杨辉三角形算法php实现,PHP实现杨辉三角形
  10. 灵遁者第一部诗歌集《触摸世界》上集40首诗歌欣赏
  11. 花生壳 linux客户端 命令
  12. ad18差分布线,设置差分对
  13. HBuilder详细安装教程
  14. shell练习Day2
  15. oppo手机文件共享媒体服务器,OPPO云服务的相片共享空间:每一个甜蜜回忆都在眼前...
  16. 精度、召回率、准确率、F1、ROC、AUC的理解
  17. 联发科mtk和骁龙730哪个好_联发科g90t和骁龙730哪个好? 配置、跑分对比
  18. 【错误异常大全】:无法加载 DLL“ArcGISVersion.dll”: 找不到指定的模块。 (异常来自 HRESULT:0x8007007E)。
  19. bibi黑马MySQL学习笔记之约束
  20. 滚动条插件vue-scroll

热门文章

  1. @符号 在 IE中的处理
  2. 对称图像输出问题(for循环 ,取绝对值的利用)
  3. 阿里云IoT Studio遇到“数据格式验证出错”怎么解决?
  4. android 自定义view 高度,自定义View之宽高的设置,全网最详解
  5. [python爬虫]--爬取豆瓣音乐topX
  6. 外贸找客户的几十种方法,总有一种适合你
  7. 相机参数标定(camera calibration)及标定结果如何使用
  8. IPV6地址分类概述
  9. 华为鸿蒙系统是否阻止广告,华为鸿蒙系统解决互联网电视痛点:首发设备欲屏蔽开机广告...
  10. 网易易盾饶晓艳:内容安全“第三方”这条路,曾经不好“走”