Save bytes in float variable

The only thing I don't understand, is why memcpy should be any better than
a reinterpret_cast of one pointer type to another
char*p = reinterpret_cast<char *>(&f);

That's the second "only thing"

My position, BTW:
Ok agreed, it's UB, you should avoid teaching it.
And byte aligning, future quantum computers or fairy magic might fool you, if you do it wrong.
But I'm sure to be able to use it anyway.

The original problem didn't show any problem with `union` etc.

This is C, not C++, and it's simply wrong to apply printf("%X", f); to a float variable

have a look here: reinterpret_cast conversion -

When it is needed to interpret the bytes of an object as a value of a different type, std::memcpy or std::bit_cast (since C++20) can be used

I suggest we stop hijacking the OP's thread and any discussion on this could be in a new thread

1 Like