Domanda

I tried following:

std::cout << std::hex << 17.0625;

But it dumped it in decimal. I'd like to see 11.01 (17.0625 in hex). How can I print some floating point value in hex?

Please do not offer solutions like:

void outhexdigits(std::ostream& out, fp_t d, int max_chars=160)
{
    while(d > 0. && max_chars)
    {
        while(d < 1. && max_chars){
            out << '0';
            --max_chars;
            d*=16;
        }

        if (d>=1. && max_chars) {
            int i = 0;
            while (d>=1.)
                ++i, --d;
            out << std::hex << i;
            --max_chars;
        }
    }
}

Is there any way to dump float numbers in hex in STL/boost?

È stato utile?

Soluzione 2

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.

Altri suggerimenti

Try cout << std::hexfloat << 1.0625; This requires C++11.

std::hexfloat is a format manipulator to print floating point values in a hexadecimal representation. It has existed since the 2011 Standard.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top