0

How convert constant float value to hex in compile time?

In runtime i do in this way:

int main()
{
    union float_to_int
    {
        float                           float_;
        int                             int_;
    };

    printf("43.2 in hex: 0x%X.\n", float_to_int{ 43.2f }.int_);

    return 0;
}

How to do this in compile time? I'm completely lost

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
cYeR
  • 145
  • 1
  • 10

1 Answers1

4

Broadly speaking... you don't. Any mechanism you might use to accomplish this will invoke UB (the one you posted certainly does), and anything UB in compile-time code is explicitly defined to be ill-formed.

Well, until C++20 which will add std::bit_cast, a function that can convert trivially copyable types by doing the equivalent of bytewise copies between them. It is defined as constexpr (so long as the source and destination types are appropriate for that action), so you can do these conversions at compile-time.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • And how is that implemented? Type punning? – Red.Wave Sep 08 '19 at 08:55
  • @Red.Wave: Type punning is when you use a piece of memory as two different objects. `bit_cast` returns a *new object*, a prvalue which has no memory overlap with the given object. Also, the standard library runs on fiat; it does what it does because the standard says it does. It doesn't need to be something that you could implement yourself. – Nicol Bolas Sep 08 '19 at 13:18
  • library used to be distinct from keywords. At least in the sense that library would be implemented inside the language(with the exception of ‘std::type_info‘). Looks like starting with ‘std:: initializer_list‘ everythings finds its way in the library rather than keyword set. If we don't stop right now, 'namespace std' becomes insanely populated with a jungle of magic types. And about punning, what prevents a function from returning a copy of punned object?(so the implementation be type_punning deep down, but returned by value) – Red.Wave Sep 08 '19 at 18:10
  • @Red.Wave: "*with the exception of ‘std::type_info‘*" So you admit that there is *precedent*, and therefore the library was never really "distinct from keywords." "*what prevents a function from returning a copy of punned object?*" That doesn't make sense. You don't pun an object per-se; you pun a *memory address*. Returning a copy of the object representation of an object is different from punning the object. – Nicol Bolas Sep 08 '19 at 18:15