Is there a well-defined and performant way to bitwise convert double to uint64_t and back

Previous similar questions which didn't answer my question:

bit cast uint64_t to double and back in a macro

Converting uint64_t to Double Value

I need to save a double to the flash memory on an STM32L476 microcontroller. The flash controller works in 64 bit chunks and the HAL APIs from ST take a uint64_t parameter for the data to write. To this end, I need to convert the bits from the double variable into one or more uint64_ts.

I tried the following, which is UB:

uint64_t flash_write_val = *(uint64_t*)&double_value;

However, I get a compiler warning about breaking strict aliasing rules. How would I do this without invoking UB? It doesn't need to be super portable. It can be valid only on a Cortex M4F core.

I'm thinking about this:

union uint64_double {
    uint64_t flash_friendly;
    double math_friendly;

Is this a good approach, or am I still shooting myself in the foot?


  • Just use memcpy to copy the bytes where you want.

    memcpy(&flash_write_val, &double_val, sizeof(double_val));