From 651ee53e958dd8f2a66a158e1793012a7325b086 Mon Sep 17 00:00:00 2001 From: Eduardo Silva Date: Fri, 26 Apr 2024 12:55:28 -0500 Subject: [PATCH] math: use memcpy to avoid losing precision Signed-off-by: Eduardo Silva --- include/cmetrics/cmt_math.h | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/include/cmetrics/cmt_math.h b/include/cmetrics/cmt_math.h index 4a91f1a..dfa659a 100644 --- a/include/cmetrics/cmt_math.h +++ b/include/cmetrics/cmt_math.h @@ -30,24 +30,30 @@ static inline uint64_t cmt_math_d64_to_uint64(double val) { + uint64_t tmp; + if (isnan(val)) { - return 0; + /* we need to decide how to handle this */ } if (isinf(val)) { - return UINT64_MAX; + /* we need to decide how to handle this */ } - if (val > (double) UINT64_MAX) { + if ((uint64_t) val > UINT64_MAX) { return UINT64_MAX; } - return (uint64_t) val; + memcpy(&tmp, &val, sizeof(double)); + return (uint64_t) (tmp); } static inline double cmt_math_uint64_to_d64(uint64_t val) { - return (double) val; + double tmp; + + memcpy(&tmp, &val, sizeof(uint64_t)); + return tmp; } #endif