From 3063df4f74bab53846f9477be7555a359741a4e9 Mon Sep 17 00:00:00 2001 From: Randy Heit Date: Fri, 1 Nov 2013 21:45:02 -0500 Subject: [PATCH] Add single <-> double conversions. - With explicit casting now possible, converting from double to single precision floating point and back again needs to be possible, too. --- src/zscript/ast.cpp | 13 +++++++++++-- src/zscript/zcc_expr.cpp | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/zscript/ast.cpp b/src/zscript/ast.cpp index bba089a301..c7ebf801e7 100644 --- a/src/zscript/ast.cpp +++ b/src/zscript/ast.cpp @@ -160,10 +160,15 @@ public: size_t len = mysnprintf(buf, countof(buf), "%08x", x); Add(buf, len); } - void AddFloat(double f) + void AddFloat(double f, bool single) { char buf[32]; size_t len = mysnprintf(buf, countof(buf), "%.4f", f); + if (single) + { + buf[len++] = 'f'; + buf[len] = '\0'; + } Add(buf, len); } private: @@ -501,7 +506,11 @@ static void PrintExprConstant(FLispString &out, ZCC_TreeNode *node) } else if (enode->Type == TypeFloat64) { - out.AddFloat(enode->DoubleVal); + out.AddFloat(enode->DoubleVal, false); + } + else if (enode->Type == TypeFloat32) + { + out.AddFloat(enode->DoubleVal, true); } else if (enode->Type == TypeName) { diff --git a/src/zscript/zcc_expr.cpp b/src/zscript/zcc_expr.cpp index da9063fc97..dc7a08d1cc 100644 --- a/src/zscript/zcc_expr.cpp +++ b/src/zscript/zcc_expr.cpp @@ -613,6 +613,21 @@ static void DtoU32(ZCC_ExprConstant *expr, FSharedStringArena &str_arena) expr->Type = TypeUInt32; } +static void FtoD(ZCC_ExprConstant *expr, FSharedStringArena &str_arena) +{ + // Constant single precision numbers are stored as doubles. + assert(expr->Type == TypeFloat32); + expr->Type = TypeFloat64; +} + +static void DtoF(ZCC_ExprConstant *expr, FSharedStringArena &str_arena) +{ + // Truncate double precision to single precision. + float poop = (float)expr->DoubleVal; + expr->DoubleVal = poop; + expr->Type = TypeFloat32; +} + static void S32toS(ZCC_ExprConstant *expr, FSharedStringArena &str_arena) { char str[16]; @@ -664,7 +679,10 @@ void ZCC_InitConversions() TypeSInt32->AddConversion(TypeFloat64, S32toD); TypeSInt32->AddConversion(TypeString, S32toS); + TypeFloat32->AddConversion(TypeFloat64, FtoD); + TypeFloat64->AddConversion(TypeUInt32, DtoU32); TypeFloat64->AddConversion(TypeSInt32, DtoS32); + TypeFloat64->AddConversion(TypeFloat32, DtoF); TypeFloat64->AddConversion(TypeString, DtoS); }