- [Psy-X] half_float.h compatible with C language

This commit is contained in:
Ilya Shurumov 2021-05-10 03:30:22 +06:00 committed by InspirationByte
parent 718b456f26
commit 14b7a526a6
2 changed files with 34 additions and 9 deletions

View File

@ -5,6 +5,7 @@ struct half
{
unsigned short sh;
#if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus)
half() {};
half(const float x);
half(const half& other);
@ -15,6 +16,18 @@ struct half
sh = other.sh;
return *this;
}
#endif
};
#if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus)
extern "C" {
#endif
extern short to_half_float(const float x);
extern float from_half_float(const short x);
#if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus)
}
#endif
#endif // HALF_FLOAT

View File

@ -26,7 +26,7 @@ union FP16
};
};
half::half(const float x)
short to_half_float(const float x)
{
// this is a approximate solution
FP32 f = *(FP32*)&x;
@ -50,17 +50,12 @@ half::half(const float x)
o.u = f.u >> 13; // Take the mantissa bits
o.u |= sign >> 16;
sh = o.u;
return o.u;
}
half::half(const half& other)
float from_half_float(const short x)
{
sh = other.sh;
}
half::operator float() const
{
FP16 h = { sh };
FP16 h = { x };
static const FP32 magic = { 113 << 23 };
static const uint shifted_exp = 0x7c00 << 13; // exponent mask after shift
@ -82,3 +77,20 @@ half::operator float() const
o.u |= (h.u & 0x8000) << 16; // sign bit
return o.f;
}
// C++ parts
half::half(const float x)
{
sh = to_half_float(x);
}
half::half(const half& other)
{
sh = other.sh;
}
half::operator float() const
{
return from_half_float(sh);
}