Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I printf() a float in hexadecimal form?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading