"how to print a single-precision float with printf" Code Answer


printf(3)'s %f format specifier wants a double. there is no way to get printf to accept a float, only double or long double.

c's default argument promotions specify that calls to variadic functions like foo(char *fmt, ...) promote float to double, and perform the usual integer promotions of narrow integer types to int, for trailing args that match the ... part of the prototype. (the same applies to all args for calling functions with no prototype.) n1570 function calls, subsections 6 and 7.

thus c provides no way for a caller to pass a float to printf, so it has no conversion for it, and %f means double. (%lf also works for double, assuming the implementation ignores it for non-integer / wchar_t conversions. accepting %lf for double is required in c99/c11 and c++11 printf implementations, so you can safely use the same %lf format string with a double for printf and scanf).

note that scanf is different, because float * and double * aren't affected by those promotions.

in this case, load with cvtss2sd .num(%rip), %xmm0.

if you look at compiler output, you'll see gcc do everything you did, and pxor-zero the register first to break the false dependency on the old value of %xmm0. (cvtss2sd's poor design leaves the upper 64 bits of the destination unchanged.) gcc errs on the side of caution, and inserts xor-zeroing instructions to break false dependencies in many cases.

you're probably getting 0 because the upper bits of xmm0 happen to be zero. when printf looks at the low 64 bits of xmm0 as a double (ieee binary64 on x86), it finds the bit pattern for 123.4f in the low 32 bits of the mantissa, and the rest zero. as a 64-bit double, this bit-pattern represents a very small (subnormal) number, so it comes out as zero with %f.

you can try the equivalent with a float, (e.g. on http://www.h-schmidt.net/floatconverter/ieee754.html), setting some bits in the low half to see what you get.

if you used %g (scientific notation) or %a (hex representation of the double bit-pattern), the non-zero bits would show up. (unless you had denormals are zero mode enabled in the mxcsr.)

By Ben Kelly on August 20 2022

Answers related to “how to print a single-precision float with printf”

Only authorized users can answer the Search term. Please sign in first, or register a free account.