Amit Singh Tomar Amit Singh Tomar - 1 year ago 77
C Question

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?

Answer Source

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:


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

That should give you


Add 5, and you get

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

Now shift it (normalize it) and adjust the exponent accordingly

1.010011001100110011001100110011... exp +2   (1.3 * 2^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.