[Math] An algorithm to convert float number to binary representation

computer science

I want to know the algorithm of converting a given float (e.g, 3.14) to binary in the memory.

I read this wikipedia page, but it only mentions about the conversion the other way.

Let me quickly give the details, from the same wikipedia page:

32 bit floating point representation

As you know; the floating number is calculated as:

$value = (-1)^ {sign} \times 2^{exponent-127} \times fraction $

where

$ exponent = 2^2 + 2^3 + 2^4 + 2^5 + 2^6 $

$ fraction = 1 + 2^{-2} $

in this example. Please check the wikipedia page for more detailed info.

So, we can calculate the float number with given binary but how can we do the other way algorithmically?

Thanks in advance.

Best Answer

enter image description here

Example: Convert 50.75 (in base 10) to binary.

First step (converting 50 (in base 10) to binary):

  1. We divide 50 by 2, which gives 25 with no remainder.
  2. Next, we divide 25 by 2, which gives 12 with a remainder of 1.
  3. We continue like this until we reach 0.
  4. We read the result from bottom to top (as shown in the picture).

Second step (converting 0.75 (in base 10) to binary):

  1. We multiply 0.75 by 2, which gives 1.5. We keep only the integer part, which is 1. Then, we do 1.5 - 1, which gives 0.5.
  2. We multiply 0.5 by 2, which gives 1. We keep only the integer part, which is 1. Then we do 1 - 1, which gives 0.
  3. We're done. We read from top to bottom (check picture).

This method can also be used to convert a float to octal or hexadecimal. Same methodology.