2

How can one format double as hex?

double t = 1.123;
fmt::format("{:x}", t);

It throws exception "invalid type specifier".

I would like to get string 3ff1f7ced916872b

TylerDense
  • 45
  • 5

1 Answers1

2

You can use std::bit_cast to cast double into an appropriately sized integer and format that in hexadecimal, e.g. assuming IEEE754 double:

  double t = 1.123;
  auto s = fmt::format("{:x}", std::bit_cast<uint64_t>(t));
  // s == "3ff1f7ced916872b"

godbolt: https://godbolt.org/z/ehKTrMz7M

vitaut
  • 49,672
  • 25
  • 199
  • 336