What is the best way(optimized by speed) to convert a short number to ascii in C (-1,5,1000 to "-1","5","1000").
I need it for embedded MCU, so the sprintf()
is not an option.
Thanks
What is the best way(optimized by speed) to convert a short number to ascii in C (-1,5,1000 to "-1","5","1000").
I need it for embedded MCU, so the sprintf()
is not an option.
Thanks
As @Potatoswatter succinctly comments, use standard itoa()
is you have it.
As to what is fastest: best to profile candidate solutions. What works best on one platform may differ on another.
Below is an alternative implementation. Flowing is a tight recursive solution that does not need to reverse its results. It works for all int
: [INT_MIN, INT_MAX]
as it works with the negative side of int
which is the same size or larger than the positive side.
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;
}
A fast solution, that returns a pointer somewhere in the buffer provided follows:
#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;
}