Skip to content
Permalink
Browse files

prf.c: properly format INF/NAN/zero with prefix

The space or plus prefix must appear when requested even with INF and
NAN. And no zero-padding in that case.

Also, 0.0 and -0.0  are distinct values. It is necessary to display
the minus sign with a negative zero.

Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
  • Loading branch information...
Nicolas Pitre authored and nashif committed Jun 20, 2019
1 parent 90ec536 commit 53169743d2b351949e9c92dc4948ac8f4f4f6c80
Showing with 19 additions and 16 deletions.
  1. +11 −16 lib/libc/minimal/source/stdout/prf.c
  2. +8 −0 tests/lib/sprintf/src/main.c
@@ -224,11 +224,15 @@ static int _to_float(char *buf, uint64_t double_temp, char c,
fract = (double_temp << 11) & ~HIGHBIT64;
sign = !!(double_temp & HIGHBIT64);

if (sign) {
*buf++ = '-';
} else if (fplus) {
*buf++ = '+';
} else if (fspace) {
*buf++ = ' ';
}

if (exp == 0x7ff) {
if (sign) {
*buf++ = '-';
}
if (!fract) {
if (isupper(c)) {
*buf++ = 'I';
@@ -261,19 +265,6 @@ static int _to_float(char *buf, uint64_t double_temp, char c,
if ((exp | fract) != 0) {
exp -= (1023 - 1); /* +1 since .1 vs 1. */
fract |= HIGHBIT64;
decexp = true; /* Wasn't zero */
} else {
decexp = false; /* It was zero */
}

if (decexp && sign) {
*buf++ = '-';
} else if (fplus) {
*buf++ = '+';
} else if (fspace) {
*buf++ = ' ';
} else {
/* unreachable */
}

decexp = 0;
@@ -615,6 +606,10 @@ int z_prf(int (*func)(), void *dest, const char *format, va_list vargs)
prefix = 1;
}
clen += zero.predot + zero.postdot + zero.trail;
if (!isdigit(buf[prefix])) {
/* inf or nan: no zero padding */
fzero = false;
}
precision = -1;
break;
}
@@ -121,6 +121,10 @@ void test_sprintf_double(void)
zassert_true((strcmp(buffer, "-INF") == 0),
"sprintf(-INF) - incorrect output '%s'\n", buffer);

sprintf(buffer, "%010f", var.d);
zassert_true((strcmp(buffer, " -inf") == 0),
"sprintf( +inf) - incorrect output '%s'\n", buffer);

var.u1 = 0x00000000;
var.u2 = 0x7ff80000; /* Bit pattern for NaN (double) */
sprintf(buffer, "%e", var.d);
@@ -147,6 +151,10 @@ void test_sprintf_double(void)
zassert_true((strcmp(buffer, "NAN") == 0),
"sprintf(NAN) - incorrect output '%s'\n", buffer);

sprintf(buffer, "%+8.5e", var.d);
zassert_true((strcmp(buffer, " +nan") == 0),
"sprintf( +nan) - incorrect output '%s'\n", buffer);

var.u1 = 0x00000000;
var.u2 = 0xfff80000; /* Bit pattern for -NaN (double) */
sprintf(buffer, "%e", var.d);

0 comments on commit 5316974

Please sign in to comment.
You can’t perform that action at this time.