Can someone explain why interpreting a float as an integer as I understand data would be lost, is it a valid C casting?
float sqrt7(float x)
{
unsigned int i = *(unsigned int*) &x;
i += 127 << 23;
i >>= 1;
return *(float*) &i;
}
In addition, after it is cast again to float, it is the first time that I see this type of code
Floating point numbers can, on the one hand, have decimal places, while an integer cannot. If you convert a number with decimals to a representation that does not support decimals, you will lose the decimal part of the number, so you will lose precision.
Another problem with this conversion is that the range of values supported by
float
is much larger than that supported byint
orunsigned int
. Forcing a conversion when the range of the target type is exceeded results in numbers that have nothing to do with it... A positive number that becomes a negative...And as a final note, the above especially affects
unsigned int
since everythingfloat
with a negative value that is converted tounsigned int
will result in a positive number that has little or nothing to do with the original number.Having said that:
Is it bad to do this kind of conversions?
Absolutely. The bad thing is doing them crazy and without being very clear that the conversion is safe. On many occasions you will find that it is unavoidable to make a conversion to communicate your program with a library... You will only have to guarantee that the conversion does not become something harmful.
Does what I comment on affect the example?
The specific example is not affected at all.
Let me explain: the example performs a conversion from
float
tounsigned int
only because binary shift instructions are not available for the typefloat
.The code is assuming that
unsigned int
andfloat
will occupy the same number of bytes. To avoid doing a data conversion (which would involve loss of lookahead), create a pointer tounsigned int
and point that pointer to float. In this way, from the point of view of the pointer, what is stored there is of typeunsigned int
, so the binary shift operations are automatically activated.If instead of a pointer a conversion of the data were made, the effects mentioned at the beginning would occur.
All the best