X-Git-Url: https://secure.softndesign.org/git/?a=blobdiff_plain;f=fdprintf.c;h=76722fc508851be20d29be71f906a06b6f3e276b;hb=89cf095594de27bde3e3be007d255cad56ab0eca;hp=58bf89d8449c0a8f3f5e02c71834afd648b6f2e1;hpb=01f02c415322b4de051a616b58de5d69a08a3a7f;p=calc.git diff --git a/fdprintf.c b/fdprintf.c index 58bf89d..76722fc 100644 --- a/fdprintf.c +++ b/fdprintf.c @@ -30,6 +30,51 @@ unsigned int nextpow (unsigned int x, int base) { return (n == 0) ? 1 : n; } +char *itoa (char *str, unsigned u, unsigned int sz) +{ + unsigned int i = (sz == 0 ) ? nextpow (u, 10) : sz; + char *s = str; + while (i > 0) { + str[i - 1] = '0' + (u % 10); + u /= 10; + i--; + s++; + } + return s; +} + +double tenpower(int n) +{ + double t = 1.0; + int i; + for (i = 0; i < n; i++) { + t *= 10; + } + for (i = 0; i > n; i--) { + t /= 10; + } + return t; +} + +int getexponant (double *f, int maxexp) +{ + int exp = 0; + while (*f > 10) { + *f /= 10; + exp++; + } + while (*f < 1) { + *f *= 10; + exp--; + } + *f += tenpower (maxexp - 1); + if (*f >= 10) { + *f /= 10; + exp++; + } + + return exp; +} /* simple fprintf function */ int fdprintf (int fd, const char *fmt, ...) @@ -41,6 +86,7 @@ int fdprintf (int fd, const char *fmt, ...) va_start (ap, fmt); while (*fmt) { char *s; + double f = 0.0; int d = 0; unsigned int u; char c = *fmt++; @@ -50,7 +96,7 @@ int fdprintf (int fd, const char *fmt, ...) *str++ = c; } else { int t = 0; - char w = '0'; + char w = '0'; int i, sz = 0; void *p = NULL; @@ -79,12 +125,37 @@ int fdprintf (int fd, const char *fmt, ...) t = 1; /* fall through */ case 'u': /* unsigned int */ - u = (t) ? (unsigned int)d : va_arg (ap, unsigned int); - for (i = nextpow (u, 10), s = str; i > 0; i--, s++) { - str[i - 1] = '0' + (u % 10); - u /= 10; + str = itoa (str, (t) ? (unsigned int)d : va_arg (ap, unsigned int), 0); + break; + case 'f': /* float */ + f = va_arg (ap, double); + if (f == 0) { + *str++ = '0'; + break; + } + if (f < 0) { + *str++ = '-'; + f = -f; + } + t = getexponant (&f, -6); + u = (int)f; + str = itoa (str, u, 0); + d = (int)((f - u) * tenpower (6)); + if (d > 0) { + *str++ = '.'; + str = itoa (str, d, 6); + } + while (*(str - 1) == '0') { + str--; + } + if (t != 0) { + *str++ = 'e'; + if (t < 0) { + *str++ = '-'; + t = -t; + } + str = itoa (str, t, 0); } - str = s; break; case 'p': /* pointer */ *str++ = '0';