Why is nan result in this floating point conversion?

float and int types are all 4 bytes, and I'm trying to convert this way:

unsigned int x = 0; // 00000000
x = ~x>>1; // 7fffffff
float f = *((float *)&x);
printf("%f\n", f);

Since the first bit in the floating-point c-number represents +/-, and the next 8 bits expin 2^(exp-127), and the rest will be converted to 0.xxxxx..., this means that I can get the maximum floating-point number: 0|11111111|111...111but finally, I get nan.

So is something wrong?

+4
source share
3 answers

You are close, but your exponent is out of range, so you have one NaN. FLT_MAX:

0 11111110 11111111111111111111111
s eeeeeeee mmmmmmmmmmmmmmmmmmmmmmm

, 11111110, 11111111 NaN s.

:

0x7f7fffff

, :

unsigned int x = 0x7f7fffff;
float f = *((float *)&x);
printf("%f\n", f);

:

3.4028235E38

IEEE-754, -, , float-: http://www.h-schmidt.net/FloatConverter/IEEE754.html

+3

(32-) IEEE ( ):

s111 1111 1xxx xxxx xxxx xxxx xxxx xxxx

s - ( ), x ( ).

+2

max float, "":

float f = FLT_MAX;
int x = *((int*)&f);
printf("0x%.8X\n",x);

0x7F7FFFFF ( 0x7FFFFFFF, ).

C sizeof(float) == sizeof(int).

Thus, you will need to test this on your platform to ensure proper execution.

+2
source

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


All Articles