Better type punning

This commit is contained in:
Deukhoofd 2022-02-11 14:06:52 +01:00
parent c239ac5220
commit c1aea15254
Signed by: Deukhoofd
GPG Key ID: F63E044490819F6F
1 changed files with 24 additions and 6 deletions

View File

@ -72,27 +72,45 @@ double fraction(double v)
}
#endif
template<typename T, typename F>
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<float*>(&raw);
// TODO: Identify CPU family to provide proper conversion
// if the CPU doesn't natively use IEEE style floats
alias_cast_t<asUINT, float> t;
t.raw = raw;
return t.data;
}
asUINT fpToIEEE(float fp)
{
return *reinterpret_cast<asUINT*>(&fp);
alias_cast_t<float, asUINT> t;
t.raw = fp;
return t.data;
}
double fpFromIEEE(asQWORD raw)
{
return *reinterpret_cast<double*>(&raw);
alias_cast_t<asQWORD, double> t;
t.raw = raw;
return t.data;
}
asQWORD fpToIEEE(double fp)
{
return *reinterpret_cast<asQWORD*>(&fp);
alias_cast_t<double, asQWORD> t;
t.raw = fp;
return t.data;
}
// closeTo() is used to determine if the binary representation of two numbers are