OK, so here's a log of my thought processes for dissecting this code. I haven't peeked below this post so this is what I came up with on my own.
Code:
union u {
float v;
uint32_t r;
};
What the heck is a union? Like I said, I dont know that much C, so its off to Google.
Ok, that makes sense. Its like a struct but only one member at a time can have data. In this case, union u is going to have either a float value or an unsigned 32-bit integer value.
Here were declaring a variable called foo that has the type of our union u. The curly braces that follow indicate an inline initialization of the foo variable. The initialization process is provided a variable x thats being cast to an int type. But, will this be assigned to the float member or the uint32_t member of the union?
Ok, so the variable x should be getting assigned to the first union member (this is the default when theres no designator specified), which is the float variable v. But what about the cast in the initialization? Does casting it to an integer type affect this in any way?
Its tempting to jump to the conclusion that casting this variable to an integer type will lead to it being assigned to the uint32 member rather than the float member, but I cant find any documentation to support this and since the C11 specification costs actual monies to read ($60 for a PDF!!!), I cant dive any further to discover how a compiler might treat this behavior. In this case, I must conclude that despite the cast, x is still being assigned to the float member v.
Code:
return (foo.r + 0x1fffff>>21) - 496;
Alright, were returning a value. Now, this is referencing the uint32 variable r which was not actually assigned, but since this is a union and the other member WAS assigned, then r will still be referring to actual data. So the integer value x shouldve been stored as the same value in the float variable v.
Now were accessing our signed integer value, converted to a float, as an unsigned 32-bit integer. This can have unexpected results, especially if the number is negative. Converting a negative signed value to an unsigned value can lead to a very high positive value. But at this point Im not sure what else to say is happening, other than adding the bit-shifted hex value and then subtracting 496.
Since the last operations are predicated on the value of an unknown variable x, I dont know how to resolve this expression to an actual value. I definitely don't know why those particular values are being added and subtracted at the end.