Why is the conclusion of this floating NaN union?

In my C ++ code, I declared a union:

typedef union U_FloatParse {
    float float_data;
    unsigned char byte_data[4];
} U_FloatConvert;

Then I set the byte_data array with values ​​0, 0, 192, 127:

U_FloatConvert depth_data;

depth_data.byte_data[0] = 0;
depth_data.byte_data[1] = 0;
depth_data.byte_data[2] = 192;
depth_data.byte_data[3] = 127;

printf("\n\nFloat = %f\n\n", depth_data.float_data);

As a conclusion, I get NaN. Why am I not getting a normal float value? When I pass the values: 56, 137, 33, 63. I get a float value of 0.631000.

Test code: http://codepad.org/Q8ds1V0F

+4
source share
3 answers

By writing the specified bytes to an array, you get a memory layout 00 00 c0 7f, which in small endian reads like 7fc00000. Interpreting this as an IEEE float gives you

  • sign 0 (positive, but not significant for NaN)
  • 0xFF
  • 0x400000 ( > 0 → )

() NaN.

, C. ++ , , NaN , , C ( , , undefined!).

+6

NaN - , NaN.

" spoon NaN", undefined ++. . -!

+6

NaN ( ), , , . i, , 0/0.

( ), , undefined .

On the one hand, floating point values ​​are mainly divided into bit fields, with so many bits containing the mantissa, so many hold an exponent, and one holds a sign. And an integer, on the other hand, is simply a representation of the number-2 base. Their bits are simply not located the same way.

You can do the following:

unsigned long int l = byte_data[0] | (byte_data[1] << 8) | (byte_data[2] << 16) | (byte_data[3] << 24);
0
source

Source: https://habr.com/ru/post/1663960/


All Articles