student student - 2 years ago 197
C Question

simplified version of return ((union { float v; uint32_t r; }){(int)x}.r>>21) - 496

I have found some code in malloc.c implementation, can anyone please tell me what does this code actually do:

return ((union { float v; uint32_t r; }){(int)x}.r>>21) - 496

I did some search and found that it converts integer to IEEE 754 floating point but I am unable to understand how it works. Can anyone please help me in understanding it in multiple steps?

Answer Source

This part is a compound literal:

(union { float v; uint32_t r; }){(int)x}

Basically is a conversion from a variable casted to int to a float (the first member of the union)

Uses this float as an uint32_t:


And removes the last 21 bits (mantissa?):


then returns the value -496

Step by step:

union t {
   float v;
   uint32_t r;

union t u;

u.v = (int)x;
u.r >>= 21;
return u.r - 496; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download