echo47 said:I can think of a couple of ways to compute the number of digits before doing the conversion:
1. A series of comparisons: Is it greater than 9? Greater than 99? Greater than 999?
2. If the number is greater than zero, calculate 1 + floor(log10(Var))
#include <stdio.h>
int main(void)
{
int digits, Var=12345;
char VarAry[20];
digits = sprintf(VarAry, "%d", Var);
printf("Var=%d VarAry=%s digits=%d\n", Var, VarAry, digits);
return 0;
}
unsigned decimal_digits(unsigned var)
{
if (var <= 9) return 1;
if (var <= 99) return 2;
if (var <= 999) return 3;
if (var <= 9999) return 4;
if (var <= 99999) return 5;
return 0; /* error, I have only five fingers on my hand */
}
echo47 said:Maybe do something like this:
Code:unsigned decimal_digits(unsigned var) { if (var <= 9) return 1; if (var <= 99) return 2; if (var <= 999) return 3; if (var <= 9999) return 4; if (var <= 99999) return 5; return 0; /* error, too many digits */ }
#include <string.h>
void itostr(unsigned int val, unsigned char *result)
{
static char buf[32] = {0};
int i = 30;
for(; val && i ; --i, val /= 10)
buf[i] = "0123456789"[val % 10];
strcpy(result,&buf[i+1]);
}
#include <string.h>
void itostr(unsigned int val, unsigned char *result)
{
static char buf[32] = {0};
int i = 30;
for(; val && i ; --i, val /= 10)
buf[i] = "0123456789"[val % 10];
strcpy(result,&buf[i+1]);
}
#include <stdio.h>
int main(void)
{
unsigned Var = 12345;
char VarAry[32];
itostr(Var, VarAry);
printf("Var=%u VarAry=%s\n", Var, VarAry);
return 0;
}
echo47 said:'itostr' is inefficient. I recommend cleaning it up before using it for serious work.
char *itos(char *s,int i)
{ char *r = s;
int t;
if (i < 0)
{ i = -i;
*s++ = '-';
}
t = i;
do
++s;
while (t /= 10);
*s = '\0';
do
*--s = '0' + i % 10;
while (i /= 10);
return s;
}
char *itos(char *s,unsigned i)
{ unsigned t = i;
do ++s; while (t /= 10);
*s = '\0';
do *--s = '0' + i % 10; while (i /= 10);
return s;
}
We use cookies and similar technologies for the following purposes:
Do you accept cookies and these technologies?
We use cookies and similar technologies for the following purposes:
Do you accept cookies and these technologies?