在C中将短数字转换为ascii的最佳方法是什么(通过速度优化)(-1,5,1000到“-1”,“5”,“1000”) .
我需要它用于嵌入式 MCU,因此 sprintf()
不是一个选项。
谢谢
最佳答案
如@Potatoswatter简洁的评论,使用标准的 itoa()
就可以了。
至于什么是最快的:最好是分析候选解决方案。在一个平台上最有效的方法在另一个平台上可能会有所不同。
下面是一个替代实现。 Flowing 是一种紧密递归解决方案,不需要反转其结果。它适用于所有 int
:[INT_MIN, INT_MAX]
,因为它适用于与 int
大小相同或大于其负数的一侧积极的一面。
static char *itoa10_helper(int n, char *s) {
if (n <= -10) {
s = itoa10_helper(n / 10, s);
}
*s = (char) ('0' - n % 10);
return ++s;
}
char* itoa10(int n, char *s) {
if (n < 0) {
*s = '-';
*itoa10_helper(n, s+1) = 0;
} else {
*itoa10_helper(-n, s) = 0;
}
return s;
}
#include <limits.h>
#include <stdio.h>
#define INT_MAX_SIZE (sizeof (int)*CHAR_BIT/3 + 3)
int main(void) {
char buf[INT_MAX_SIZE];
puts(itoa10(0, buf));
puts(itoa10(123, buf));
puts(itoa10(INT_MAX, buf));
puts(itoa10(INT_MIN, buf));
return 0;
}
<小时/>
一个快速解决方案,它在提供的缓冲区中某处返回一个指针,如下所示:
#include <stdbool.h>
char* itoa10f(int n, char *buf) {
char *s = buf + INT_MAX_SIZE - 1;
*s = '\0';
bool isnegative = n < 0;
if (!isnegative) {
n = -n;
}
do {
*(--s) = (char) ('0' - n % 10);
} while (n /= 10);
if (isnegative) {
*(--s) = '-';
}
return s;
}
关于c - 如何将短格式转换为 ASCII?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29466549/