Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why the result is nan in this c float conversion?

Tags:

c

types

float and int types are all 4 bytes and I try converting in this way:

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

Because the first bit in c float number represents +/- and the next 8 bits is exp in 2^(exp-127) and the rest will be converted to 0.xxxxx..., it means I can get max float number:0|11111111|111...111 but finally I get a nan.

So is there anything wrong?

like image 736
Hayes Pan Avatar asked Mar 18 '23 13:03

Hayes Pan


2 Answers

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

0 11111110 11111111111111111111111
s eeeeeeee mmmmmmmmmmmmmmmmmmmmmmm

Note that the max exponent is 11111110, as 11111111 is reserved for NaNs.

The corresponding hex value is:

0x7f7fffff

So your code should be:

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

and the result will be:

3.4028235E38

If you're interested in IEEE-754 format then check out this handy online calculator which converts between binary, hex and float formats: http://www.h-schmidt.net/FloatConverter/IEEE754.html

like image 57
Paul R Avatar answered Mar 24 '23 04:03

Paul R


A bit-wise IEEE floating-point standard single precision (32-bit) NaN(Not a Number) would be:

s111 1111 1xxx xxxx xxxx xxxx xxxx xxxx

where s is the sign (most often ignored in applications) and x is non-zero (the value zero encodes infinities).

like image 43
justmscs Avatar answered Mar 24 '23 05:03

justmscs