Search code examples
c++c++14c++17compile-time-constant

How convert constant float value to 4 bytes hex constant value in compile time?


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


Solution

  • 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.