Interpret float as unsigned int

0

Can anyone explain why interpreting a float as an integer as I understand would be lost data, is a C casting valid?

float sqrt7(float x)
{
   unsigned int i = *(unsigned int*) &x;
   i  += 127 << 23;
   i >>= 1; 
   return *(float*) &i;
}   

Also after it re-casts to float, it's the first time I see this kind of codes

    
asked by cheroky 01.11.2016 в 15:33
source

1 answer

2

Floating-point numbers can, on the one hand, have decimals, while an integer can not. 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.

float num_decimal = 10.5;
int num_entero = (int)num_decimal;
printf("%d",num_entero); // imprime 10

Another problem that this conversion may have is that the range of values supported by float is much greater than that supported by int or unsigned int . Forcing a conversion when the range of the target type is exceeded results in numbers that have nothing to do ... A positive number that becomes negative ...

And as a final note, the above affects especially the unsigned int since all float with negative value that becomes unsigned int will result in a positive number that little or nothing will have to do with the original number .

That said:

Is it bad to do this type of conversion?

Not at all. The bad thing is to make them crazy and without being very clear that the conversion is safe. In many occasions you will find that it is inevitable to make a conversion to communicate your program with a library ... You will only have to guarantee that the conversion does not become harmful.

What do I say that affects the example?

The concrete example does not affect him absolutely nothing.

Let me explain: the example performs a conversion from float to unsigned int only because binary shift instructions are not available for type float .

The code is assuming that unsigned int and float are going to occupy the same number of bytes. To avoid doing a data conversion (which would imply loss of forecast), create a pointer to unsigned int and make that pointer point to the float. In this way from the point of view of the pointer what is stored there is of type unsigned int , so the binary displacement operations automatically activate.

If, instead of a pointer, a conversion of the data were made, the effects mentioned at the beginning would be produced.

Greetings

    
answered by 01.11.2016 / 21:17
source