]> git.tdb.fi Git - libs/datafile.git/blobdiff - source/binfloat.h
Move the definition of Input's operator bool to the header
[libs/datafile.git] / source / binfloat.h
index d16570fc057fa296a349f2b69bb167d68a960ceb..db3e92431823627249365d83f814b9f991a751c0 100644 (file)
@@ -1,7 +1,9 @@
 #ifndef MSP_DATAFILE_BINFLOAT_H_
 #define MSP_DATAFILE_BINFLOAT_H_
 
-#include "type.h"
+#include <climits>
+#include <cstdint>
+#include <cstring>
 
 namespace Msp {
 namespace DataFile {
@@ -18,45 +20,54 @@ struct BinFloat
 {
        struct Bits
        {
-               unsigned exponent;
-               unsigned mantissa;
+               unsigned exponent = 8;
+               unsigned mantissa = 23;
 
                Bits(unsigned);
        };
 
        template<typename T>
-       union Conversion
-       {
-               T f;
-               typename MatchingInt<T>::UnsignedType i;
-       };
+       struct MatchingInt;
 
-       bool sign;
-       bool infinity;
-       int exponent;
-       UInt64 mantissa;
+       bool sign = false;
+       bool infinity = false;
+       int exponent = 0;
+       std::uint64_t mantissa = 0;
 
-       static BinFloat explode(UInt64, const Bits &);
+       static BinFloat explode(std::uint64_t, const Bits &);
 
        template<typename T>
-       static BinFloat explode_iec559(T v)
-       {
-               Conversion<T> c;
-               c.f = v;
-               return explode(c.i, sizeof(T)*CHAR_BIT);
-       }
+       static BinFloat explode_iec559(T v);
 
-       UInt64 compose(const Bits &);
+       std::uint64_t compose(const Bits &);
 
        template<typename T>
-       T compose_iec559()
-       {
-               Conversion<T> c;
-               c.i = compose(sizeof(T)*CHAR_BIT);
-               return c.f;
-       }
+       T compose_iec559();
 };
 
+template<>
+struct BinFloat::MatchingInt<float> { typedef std::uint32_t Type; };
+
+template<>
+struct BinFloat::MatchingInt<double> { typedef std::uint64_t Type; };
+
+template<typename T>
+inline BinFloat BinFloat::explode_iec559(T v)
+{
+       typename MatchingInt<T>::Type i;
+       memcpy(&i, &v, sizeof(T));
+       return explode(i, sizeof(T)*CHAR_BIT);
+}
+
+template<typename T>
+inline T BinFloat::compose_iec559()
+{
+       typename MatchingInt<T>::Type i = compose(sizeof(T)*CHAR_BIT);
+       T v;
+       memcpy(&v, &i, sizeof(T));
+       return v;
+}
+
 } // namespace DataFile
 } // namespace Msp