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
904 views
in Technique[技术] by (71.8m points)

floating point - How to represent FLOAT number in memory in C

While reading a tutorial I came across how to represent Float number in memory. The tutorial had an example with a floating point number.

   float a=5.2  with below Diagram

enter image description here

Can anyone please tell how this 5.2 is converted in to binary and how it is represented in memory in above the above diagram?

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

As was said, 5.2 is represented as a sign bit, an exponent and a mantissa. How do you encode 5.2?

5 is easy:

101. 

The rest, 0.2 is 1/5, so divide 1.00000... (hex) by 5 and you get 0.3333333... (hex).

(This can be followed more easily if you consider one bit less: 0.FFFF...F / 5 = 3, so it is easy to see that 0.FFFF... / 5 = 0.33333.... That one missing bit doesn't matter when dividing by 5, so 1.0000... / 5 = 0.3333... too).

That should give you

0.0011001100110011001100110011... 

Add 5, and you get

101.00110011001100110011...         exp 0    (== 5.2 * 2^0)

Now shift it right (normalize it, i.e. make sure the top bit is just before the decimal point) and adjust the exponent accordingly:

1.010011001100110011001100110011... exp +2   (== 1.3 * 2^2 == 5.2)

Now you only have to add the bias of 127 (i.e. 129 = 0b10000001) to the exponent and store it:

0 10000001 1010 0110 0110 0110 0110 0110 

Forget the top 1 of the mantissa (which is always supposed to be 1, except for some special values, so it is not stored), and you get:

01000000 10100110 01100110 01100110

Now you only have to decide little or big endian.

This is not exactly how it works, but that is more or less what happens when a number like 5.2 is converted to binary.


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

...