From c1aea152542dbfbf868b6531d7eddb211d6aa0c8 Mon Sep 17 00:00:00 2001 From: Deukhoofd Date: Fri, 11 Feb 2022 14:06:52 +0100 Subject: [PATCH] Better type punning --- add_on/scriptmath/scriptmath.cpp | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/add_on/scriptmath/scriptmath.cpp b/add_on/scriptmath/scriptmath.cpp index c5b86c3..6d9a62c 100644 --- a/add_on/scriptmath/scriptmath.cpp +++ b/add_on/scriptmath/scriptmath.cpp @@ -72,27 +72,45 @@ double fraction(double v) } #endif +template +struct alias_cast_t +{ + union + { + F raw; + T data; + }; +}; + // As AngelScript doesn't allow bitwise manipulation of float types we'll provide a couple of // functions for converting float values to IEEE 754 formatted values etc. This also allow us to // provide a platform agnostic representation to the script so the scripts don't have to worry // about whether the CPU uses IEEE 754 floats or some other representation float fpFromIEEE(asUINT raw) { - // TODO: Identify CPU family to provide proper conversion - // if the CPU doesn't natively use IEEE style floats - return *reinterpret_cast(&raw); + // TODO: Identify CPU family to provide proper conversion + // if the CPU doesn't natively use IEEE style floats + alias_cast_t t; + t.raw = raw; + return t.data; } asUINT fpToIEEE(float fp) { - return *reinterpret_cast(&fp); + alias_cast_t t; + t.raw = fp; + return t.data; } double fpFromIEEE(asQWORD raw) { - return *reinterpret_cast(&raw); + alias_cast_t t; + t.raw = raw; + return t.data; } asQWORD fpToIEEE(double fp) { - return *reinterpret_cast(&fp); + alias_cast_t t; + t.raw = fp; + return t.data; } // closeTo() is used to determine if the binary representation of two numbers are