Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dump hex float in C++

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?

like image 401
Sergei Krivonos Avatar asked Dec 18 '13 16:12

Sergei Krivonos


3 Answers

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

like image 102
Charles Pehlivanian Avatar answered Nov 09 '22 07:11

Charles Pehlivanian


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.

like image 40
Ali Avatar answered Nov 09 '22 07:11

Ali


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

like image 21
BoBTFish Avatar answered Nov 09 '22 09:11

BoBTFish