In C we can produce hexadecimal floating point literals and we can also use printf() to output them in decimal string form:
printf("%f\n", 0x1.0p8); // Prints 256.00000
How can I output a floating point number in hexadecimal form in a way that will preserve precision? (All hexadecimal floating point literals are dyadic rationals and thus will be representable in floating point unlike decimal literals)
printf("%MAGIC\n", 0x1.0p8) // Prints 100.00000
My research only found results related to printing the bytes of the underlying representation in hexadecimal form but not how to print the value of a float in hexadecimal form
>Solution :
You can use the %a format to print a floating point number in a precision-preserving hexadecimal format. From the man page:
The double argument is rounded and converted to hexadecimal notation in the style [-]0xh.hhhp[±]d, where the number of digits after the hexadecimal-point character is equal to the precision specification. If the precision is missing, it is taken as enough to represent the floating-point number exactly, and no rounding occurs. If the precision is zero, no hexadecimal-point character appears. The p is a literal character ‘p’, and the exponent consists of a positive or negative sign followed by a decimal number representing an exponent of 2. The A conversion uses the prefix “0X” (rather than “0x”), the letters “ABCDEF” (rather than “abcdef”) to represent the hex digits, and the letter ‘P’ (rather than ‘p’) to separate the mantissa and exponent.