Skip to content

[sprintf] Wrong formatting of nan/inf with leading 0 #1781

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
stefano-zanotti-88 opened this issue May 4, 2025 · 0 comments
Open

[sprintf] Wrong formatting of nan/inf with leading 0 #1781

stefano-zanotti-88 opened this issue May 4, 2025 · 0 comments

Comments

@stefano-zanotti-88
Copy link
Contributor

In a footnote, the standard says:

When applied to infinite and NaN values, the -, +, and space flag characters have their usual meaning; the # and 0 flag characters have no effect.

STB vs standard-conforming implementation (notice also the wrong upper/lower case, already reported):

printf("%f", STB_POS_QNAN);   // "NaN"    vs "nan"
printf("%f", STB_NEG_QNAN);   // "-NaN"   vs "-nan"
printf("%f", STB_POS_SNAN);   // "NaN"    vs "nan"
printf("%f", STB_NEG_SNAN);   // "-NaN"   vs "-nan"
printf("%f", 0/0.0);          // "-NaN"   vs "-nan" or "nan" (the sign of nans is not guaranteed)
printf("%f", +1/0.0);         // "Inf"    vs "inf"
printf("%f", -1/0.0);         // "-Inf"   vs "-inf"
printf("%06f", STB_POS_QNAN); // "000NaN" vs "   nan"
printf("%06f", STB_NEG_QNAN); // "-00NaN" vs "  -nan"
printf("%06f", STB_POS_SNAN); // "000NaN" vs "   nan"
printf("%06f", STB_NEG_SNAN); // "-00NaN" vs "  -nan"
printf("%06f", 0/0.0);        // "-00NaN" vs "  -nan"
printf("%06f", +1/0.0);       // "000Inf" vs "   inf"
printf("%06f", -1/0.0);       // "-00Inf" vs "  -inf"

Reproducible nans for testing can be generated this way:

double make_nan(int sign, int signaling)
{
    unsigned long long v = ((sign ? 1ull : 0ull) << 63)
        | (0x7FFull << 52)
        | (signaling ? 1ull : (1ull << 51))
        ;
    double d;
    memcpy(&d, &v, 8);
    return d;
}
#define STB_POS_QNAN    make_nan(0, 0)
#define STB_NEG_QNAN    make_nan(1, 0)
#define STB_POS_SNAN    make_nan(0, 1)
#define STB_NEG_SNAN    make_nan(1, 1)

Fix: in both the doexpfromg: and dofloatfromg: code paths, add this:

if (dp == STBSP__SPECIAL) {
   fl &= ~STBSP__LEADINGZERO;
   s = (char *)sn;
   cs = 0;
   pr = 0;
   goto scopy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant