Others have already suggested a C++11 solution but your question doesn't have the C++11 tag. Here is an ISO C99 solution, using the %a
and %la
format specifiers from the ISO C99 Standard.
I'd like to see 11.01 (17.0625 in hex).
The following program prints 0X1.11P+4
.
#include <stdio.h>
int main() {
double x = 17.0625;
printf("17.0625 in hexadecimal is: %A\n", x);
}
Here is an example showing how to read and write floating point numbers in hexadecimal format.
#include <stdio.h>
int main() {
double x = 0.1;
char* str = "0X1.999999999999AP-4";
printf("0.1 in hexadecimal is: %A\n", x);
printf("Now reading %s\n", str);
/* in a production code I would check for errors */
sscanf(str, "%lA", &x); /* note: %lA is used! */
printf("It equals %g\n", x);
}
If portability matters or you are stuck with an older compiler, it is a reasonable approach in my opinion.