Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

floating point - Representation of float in C

I was trying to understand the floating point representation in C using this code (both float and int are 4 bytes on my machine):

int x = 3;
float y = *(float*) &x;
printf("%d %e 
", x, y);

We know that the binary representation of x will be the following

00000000000000000000000000000011

Therefore I would have expected y to be represented as follows

  • Sign bit (first bit from left) = 0

  • Exponent (bits 2-9 from left) = 0

  • Mantissa (bits 10-32): 1 + 2^(-22)+2^(-23)

Leading to y = (-1)^0 * 2^(0-127) * (1+2^(-22) + 2^(-23)) = 5.87747E-39

My program however prints out

3 4.203895e-45

That is, y has the value 4.203895e-45 instead of 5.87747E-39 as I expected. Why does this happen. What am I doing wrong?

P.S. I have also printed the values directly from gdb so it is not a problem with the printf command.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IEEE floating point numbers with exponent fields of all 0 are 'denormalized'. This means that the implicit 1 in front of the mantissa no longer is active. This allows really small numbers to be represented. See This wikipedia article for more explanation. In your example the result would be 3 * 2^-149


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...