How to get a float with a given bit pattern (like int32_t) in C ++?

I need a quick way to get a float with a given bit pattern (provided as int32_t ). Of course, the compiler must optimize the whole design. A simple conversion does the listing and reinterpret_cast<> not allowed ...

+4
source share
2 answers

It is not true that the compiler will optimize this, but it avoids UB provided that the supplied value is indeed a float representation (that is, its right size and its bitmap do not contain a trap float representation). GCC, at least sometimes, can optimize it:

 float convert(int32_t inputvalue) { float f; std::memcpy(&f, &inputvalue, sizeof(f)); return f; } 

If optimization is an important part of the question, then the official answer is that it is not possible to guarantee that an unknown compiler will perform the given optimization. But this is harder to optimize than most. It relies on a compiler to β€œunderstand” what memcpy does, which is more in demand than to β€œunderstand” what a pointer listing does.

+5
source

The only fully portable method is memcpy through the buffer:

 static_assert(sizeof(float) == sizeof(int32_t), "!!"); char buf[sizeof(float)]; memcpy(buf, &i, sizeof(buf)); memcpy(&f, buf, sizeof(buf)); 

You can usually delete a buffer:

 static_assert(sizeof(float) == sizeof(int32_t), "!!"); memcpy(&f, &i, sizeof(float)); 
+2
source

All Articles