From 708ef339d3e4d3661c8b3a75e3b01bafbed0f568 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Sun, 29 Aug 2021 13:33:54 +0300 Subject: [PATCH] Perform bit conversion using standard-sanctioned memcpy method The compiler should be able to optimize it away. --- source/binfloat.h | 23 +++++++---------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/source/binfloat.h b/source/binfloat.h index 2c74441..e50b320 100644 --- a/source/binfloat.h +++ b/source/binfloat.h @@ -29,9 +29,6 @@ struct BinFloat template struct MatchingInt; - template - union Conversion; - bool sign; bool infinity; int exponent; @@ -54,27 +51,21 @@ struct BinFloat::MatchingInt { typedef std::uint32_t Type; }; template<> struct BinFloat::MatchingInt { typedef std::uint64_t Type; }; -template -union BinFloat::Conversion -{ - T f; - typename MatchingInt::Type i; -}; - template inline BinFloat BinFloat::explode_iec559(T v) { - Conversion c; - c.f = v; - return explode(c.i, sizeof(T)*CHAR_BIT); + typename MatchingInt::Type i; + memcpy(&v, &i, sizeof(T)); + return explode(i, sizeof(T)*CHAR_BIT); } template inline T BinFloat::compose_iec559() { - Conversion c; - c.i = compose(sizeof(T)*CHAR_BIT); - return c.f; + typename MatchingInt::Type i = compose(sizeof(T)*CHAR_BIT); + T v; + memcpy(&v, &i, sizeof(T)); + return v; } } // namespace DataFile -- 2.43.0