将整数转换为字符数组函数
Convert integer to char array function
我想把一个数字转换成一个没有任何预定义的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
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 打印 2D 动态数组 c++ 函数
- C++数组函数
- 在数组函数指针中调用void
- 数组函数似乎没有找到最大值
- 使用数组函数和循环求解伪元编码|C
- 在头文件中的函数原型中获取指针数组:函数声明为 void
- 数组函数错误输出
- 读取文件,然后创建数组函数C++
- 指针数组函数参数-奇怪的行为
- 二维数组 - 函数
- "return"没有从数组函数返回正确的值
- 数组函数问题
- 数组函数的大小返回 int 的大小而不是数组
- 从数组函数中删除元素
- 如何从C++中最好地调用具有C99风格数组函数签名的函数
- 追加/打印/插入数组c++函数问题
- 如何将数组函数转换为指针函数
- 多维数组函数输出垃圾
- C++:数组函数的递归最大值