From ac7e3bf7237c12ac5a43fef52d42d31779cd62f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20Van=C4=9Bk?= Date: Mon, 30 Sep 2024 09:54:56 +0200 Subject: [PATCH] Use union for int-float type conversion Union based type punning seems to be safer for int-float type conversion as it works around strict aliasing rules, which improves portability. PR: https://github.com/deathkiller/jazz2-native/pull/80 diff --git a/Sources/nCine/Base/Algorithms.cpp b/Sources/nCine/Base/Algorithms.cpp index 99fa88bf..e7805fda 100644 --- a/Sources/nCine/Base/Algorithms.cpp +++ b/Sources/nCine/Base/Algorithms.cpp @@ -247,12 +247,16 @@ namespace nCine static inline std::uint32_t as_uint32(const float x) { - return *(std::uint32_t*)&x; + union {float f; uint32_t i;} u; + u.f = x; + return u.i; } static inline float as_float(const std::uint32_t x) { - return *(float*)&x; + union {float f; uint32_t i;} u; + u.i = x; + return u.f; } float halfToFloat(std::uint16_t value)