Reputation: 45464
I need a fast way to obtain the float
with a given bit-pattern (provided as int32_t
). Of course, the compiler should optimise the whole construction away. Simple conversion does a cast and reinterpret_cast<>
is not allowed ...
Upvotes: 4
Views: 938
Reputation: 279375
It's not reliable that the compiler will optimize this away, but it avoids UB provided that the value supplied really is a representation of a float (that is, it's the right size and its bit pattern doesn't hold a trap representation of float
). GCC is at least sometimes capable of optimizing it away:
float convert(int32_t inputvalue) {
float f;
std::memcpy(&f, &inputvalue, sizeof(f));
return f;
}
If the optimization is an important part of the question then the official answer is that there is no way to guarantee that an unknown compiler will make a given optimization. But this one is harder to optimize than most. It relies on the compiler "understanding" what memcpy
does, which is a bigger ask than "understanding" what a pointer cast does.
Upvotes: 5
Reputation: 157444
The only fully portable method is to memcpy
via a buffer:
static_assert(sizeof(float) == sizeof(int32_t), "!!");
char buf[sizeof(float)];
memcpy(buf, &i, sizeof(buf));
memcpy(&f, buf, sizeof(buf));
Usually the buffer can be elided:
static_assert(sizeof(float) == sizeof(int32_t), "!!");
memcpy(&f, &i, sizeof(float));
Upvotes: 2