Skip to content

Commit f6f31a9

Browse files
authored
[rtextures] Fix HalfToFloat() and FloatToHalf() dereferencing issues with an union (#4729)
* Fix HalfToFloat() and FloatToHalf() dereferencing issues with an union * Remove unnecessary initialization * Moved the union to inside the functions
1 parent 53ea275 commit f6f31a9

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/rtextures.c

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5390,13 +5390,19 @@ static float HalfToFloat(unsigned short x)
53905390
{
53915391
float result = 0.0f;
53925392

5393+
union
5394+
{
5395+
float fm;
5396+
unsigned int ui;
5397+
} uni;
5398+
53935399
const unsigned int e = (x & 0x7C00) >> 10; // Exponent
53945400
const unsigned int m = (x & 0x03FF) << 13; // Mantissa
5395-
const float fm = (float)m;
5396-
const unsigned int v = (*(unsigned int *)&fm) >> 23; // Evil log2 bit hack to count leading zeros in denormalized format
5397-
const unsigned int r = (x & 0x8000) << 16 | (e != 0)*((e + 112) << 23 | m) | ((e == 0)&(m != 0))*((v - 37) << 23 | ((m << (150 - v)) & 0x007FE000)); // sign : normalized : denormalized
5401+
uni.fm = (float)m;
5402+
const unsigned int v = uni.ui >> 23; // Evil log2 bit hack to count leading zeros in denormalized format
5403+
uni.ui = (x & 0x8000) << 16 | (e != 0)*((e + 112) << 23 | m) | ((e == 0)&(m != 0))*((v - 37) << 23 | ((m << (150 - v)) & 0x007FE000)); // sign : normalized : denormalized
53985404

5399-
result = *(float *)&r;
5405+
result = uni.fm;
54005406

54015407
return result;
54025408
}
@@ -5406,7 +5412,14 @@ static unsigned short FloatToHalf(float x)
54065412
{
54075413
unsigned short result = 0;
54085414

5409-
const unsigned int b = (*(unsigned int *) & x) + 0x00001000; // Round-to-nearest-even: add last bit after truncated mantissa
5415+
union
5416+
{
5417+
float fm;
5418+
unsigned int ui;
5419+
} uni;
5420+
uni.fm = x;
5421+
5422+
const unsigned int b = uni.ui + 0x00001000; // Round-to-nearest-even: add last bit after truncated mantissa
54105423
const unsigned int e = (b & 0x7F800000) >> 23; // Exponent
54115424
const unsigned int m = b & 0x007FFFFF; // Mantissa; in line below: 0x007FF000 = 0x00800000-0x00001000 = decimal indicator flag - initial rounding
54125425

0 commit comments

Comments
 (0)