将整数转换为字符数组函数

Convert integer to char array function

本文关键字:数组 函数 字符 整数 转换      更新时间:2023-10-16

我想把一个数字转换成一个没有任何预定义的C/c++函数(例如itoa)的非零终止字符数组。我没有太多的空间(在一个5KB pgm空间的嵌入式应用程序上工作,其中我已经使用了4.862KB),我的输出函数不接受零终止字符数组;只有一个数组和长度。

编辑1:我不是在公司工作:p

编辑2:Doesn't accept表示如果数组中有一个0字节,它没有任何理由不发送。

编辑3:我使用下面"Vlad from Moscow"方法的修改版本解决了这个问题。仍然感谢你们所有人,谁试图帮助我:)

编辑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类型的对象。

如果你需要在函数中分配字符数组,那么它将更简单,并且可以是非递归的。

通用算法:

我个人不推荐递归算法,除非我知道嵌入式系统施加的堆栈限制(例如pic具有非常有限的堆栈深度)以及您当前的堆栈使用情况。

origin number = 145976

newnumber = orignumber 
newnumber = new number / 10
remainder = new number % 10    answer: 6
digit = remainder + 30 hex -> store into array  answer:0x36  ascii 6
increment array location
newnumber = new number / 10
remainder = new number % 10    answer: 7
digit = remainder + 30 hex -> store into array  answer:0x37  ascii 7
increment array location
newnumber = new number / 10
remainder = new number % 10    answer: 9
digit = remainder + 30 hex -> store into array  answer:0x39  ascii 9
increment array location
repeat these 4 steps while new number > 0  
Array will contain: 0x36 0x37 0x39 0x35 0x34 0x31
null terminal array, 

null终止可以方便地计算字符串长度和字符串反转。另一种选择是从末尾开始填充数组,方法是指针自减,以避免字符串反转。

Array will contain: 0x36 0x37 0x39 0x35 0x34 0x31 0x00
finally reverse array
Array will contain: 0x31 0x34 0x35 0x39 0x37 0x36 0x00