gpt4 book ai didi

c++ - 将整数转换为字符数组函数

转载 作者:行者123 更新时间:2023-11-30 20:14:47 25 4
gpt4 key购买 nike

我想将数字转换为非零终止的字符数组,无需任何预定义的 C/C++ 函数(例如 itoa)。我没有太多剩余空间(正在使用总共 5KB pgm 空间的嵌入式应用程序,其中我已准备好使用 4.862KB),并且我的输出函数不接受以零结尾的字符数组;只有一个数组和长度。

编辑 1:我不为公司工作:P

编辑2:不接受意味着如果数组中有0字节,它就无缘无故地不会发送。

编辑3:我使用下面“来自莫斯科的弗拉德”方法的修改版本解决了这个问题。仍然感谢你们所有人,谁试图帮助我:)

编辑 4:如果有人关心:该项目正在使用蓝牙设置基于 AVR 的闹钟。

最佳答案

由于我的时薪等于零(我失业了),那么我将展示一种可能的方法。:)

我认为最简单的方法是编写递归函数。例如

#include <iostream>

size_t my_itoa( char *s, unsigned int n )
{
const unsigned base = 10;
unsigned digit = n % base;
size_t i = 0;

if ( n /= base ) i += my_itoa( s, n );

s[i++] = digit + '0';

return i;
}

int main()
{
unsigned x = 12345;
char s[10];

std::cout.write( s, my_itoa( s, x ) );

return 0;
}

输出为

12345

虽然我使用了unsigned int,但您可以修改该函数以使其接受 int 类型的对象。

如果需要在函数中分配字符数组,那就更简单了,而且可以是非递归的。

关于c++ - 将整数转换为字符数组函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24343911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com