Question

Lets suppose I have 0.128 or 0.008. The fraction cannot be represented in binary fixed point, so I don't know how to find out the mantissa in order to convert it to a floating point.

Lets suppose i have int 100, a floating point binary string will be: 01000010110010000000000000000000. I want to do the same for 0.128 , but i dont know to to round the fraction,because i need this for the manttissa.

Was it helpful?

Solution

To convert to binary the fractional part of a decimal number, you can multiply succesively the fractional part by 2. Each product will produce a 0 or a 1 in the integer part, which will be each digit of the binary representation (in order from left to right).

You can continue multiplying until the fractional part is 0, or until you obtain the number of digits needed (and then truncate or round).

Note that only the fractional numbers that are sum of negative powers of two will have an exact representation. You'll find that decimal numbers with a few digits are periodic in base 2.

From your examples the binary representation of 0.008 will start with 0.00000010...

0.008 x 2 = 0.016  First fractional digit is 0
0.016 x 2 = 0.032
0.032 x 2 = 0.064
0.064 x 2 = 0.128
0.128 x 2 = 0.256
0.256 x 2 = 0.512
0.512 x 2 = 1.024  First one
0.024 x 2 = 0.048
...

Note that multiplying by 2 in base two is equivalent to a shift to the left, or to move the dot to the right one digit, hence moving to the integer part the first fractional digit.

OTHER TIPS

Try this float to bit converter it should help you to understand how it works.

Example:

Target number 3.75

  1. Convert it to the powers of 2 (integral part is sum of positive powers and fractional is sum of negative powers)

    5.75 = 1*2^2 + 0*2^1 + 1*2^0 + 1*2^(-1) + 1*2^(-2) or in binary form

    101.11

  2. Normalize mantisa, all numbers should start with 1

    1.0111*e^2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top