How to represent FLOAT number in memory in C

Viewed 72714

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?

11 Answers

Representing 5.2 is very simple in binary logic:

     8 4 2 1
5 -> 0 1 0 1

For a decimal number:

Take .2 and multiply by 2 (since it is represented in binary).

.2 X 2 = 0.4 -> take the value after the
                decimal point, don't take the value before
                the decimal point

.4 X 2 = 0.8
.8 X 2 = 1.6
.6 X 2 = 1.2
.2 X 2 = 0.4

and so on...

After this step, take the value before the decimal point from output of the above steps:

.2 X 2 = 0.4 -> take 0 from this for representing in binary form

So the final o/p of 5.2 is:

0101.00110...
int a;
float b=5.2;
memcpy(&a, &b, 4);
printf("%d",a);

This gives 0100 0000 1010 0110 0110 0110 1000 0001 (1084647041)

Related