In the next question:
What is the correct way to enter floating point numbers in int and vice versa? , the conclusion is that the way to create doubles from whole bits and vice versa memcpy
.
This is good, and the conversion method pseudo_cast
found is found:
template <typename T, typename U>
inline T pseudo_cast(const U &x)
{
static_assert(sizeof(T) == sizeof(U));
T to;
std::memcpy(&to, &x, sizeof(T));
return to;
}
and I would use it as follows:
int main(){
static_assert(std::numeric_limits<double>::is_iec559);
static_assert(sizeof(double)==sizeof(std::uint64_t));
std::uint64_t someMem = 4614253070214989087ULL;
std::cout << pseudo_cast<double>(someMem) << std::endl;
}
My interpretation of just reading the standard and cppreference is / was that it should also be possible to use memmove
to change the effective type in place, for example:
template <typename T, typename U>
inline T& pseudo_cast_inplace(U& x)
{
static_assert(sizeof(T) == sizeof(U));
T* toP = reinterpret_cast<T*>(&x);
std::memmove(toP, &x, sizeof(T));
return *toP;
}
template <typename T, typename U>
inline T pseudo_cast2(U& x)
{
return pseudo_cast_inplace<T>(x);
}
- ( cv , 5 cppreference/reinterpret_cast). memcpy
memmove
(ยง6.9.2), T U .
? gcc clang.
memmove
,
to cppreference std:: memmove memmove,
: , , dest.
: ( segfault), @hvd. ! , ?