Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto convert decimal (xx.xx) to binary

Tags:

decimal

binary

This isn't necessarily a programming question but i'm sure you folks know how to do it. How would i convert floating point numbers into binary.

The number i am looking at is 27.625.

27 would be 11011, but what do i do with the .625?

like image 911
Ian McCullough Avatar asked Sep 23 '10 17:09

Ian McCullough


People also ask

How do you convert a decimal to a binary?

The simplest way to convert a decimal number to a binary number is by dividing the given number repeatedly by 2 until we get 0 as the quotient. Then, we write the remainders in the reverse order to get the binary value of the given decimal number.

What is the binary 101001 to decimal?

Detailed Solution So, the decimal equivalent of the binary number (101001)2 is (41)10. ∴ The number at the place of the question mark will be 41.

How do you convert .75 to binary?

Therefore, the binary equivalent of decimal number 75 is 1001011.


3 Answers

On paper, a good algorithm to convert the fractional part of a decimal number is the "repeated multiplication by 2" algorithm (see details at http://www.exploringbinary.com/base-conversion-in-php-using-bcmath/, under the heading "dec2bin_f()"). For example, 0.8125 converts to binary as follows:

1. 0.8125 * 2 = 1.625
2. 0.625 * 2 = 1.25
3. 0.25 * 2 = 0.5
4. 0.5 * 2 = 1.0

The integer parts are stripped off and saved at each step, forming the binary result: 0.1101.

If you want a tool to do these kinds of conversions automatically, see my decimal/binary converter.

like image 81
Rick Regan Avatar answered Sep 22 '22 14:09

Rick Regan


Assuming you are not thinking about inside a PC, just thinking about binary vs decimal as physically represented on a piece of paper:

You know .1 in binary should be .5 in decimal, so the .1's place is worth .5 (1/2)

the .01 is worth .25 (1/4) (half of the previous one)

the .001 is worth (1/8) (Half of 1/4)

Notice how the denominator is progressing just like the whole numbers to the left of the decimal do--standard ^2 pattern? The next should be 1/16...

So you start with your .625, is it higher than .5? Yes, so set the first bit and subtract the .5

.1 binary with a decimal remainder of .125

Now you have the next spot, it's worth .25dec, is that less than your current remainder of .125? No, so you don't have enough decimal "Money" to buy that second spot, it has to be a 0

.10 binary, still .125 remainder.

Now go to the third position, etc. (Hint: I don't think there will be too much etc.)

like image 24
Bill K Avatar answered Sep 21 '22 14:09

Bill K


There are several different ways to encode a non-integral number in binary. By far the most common type are floating point representations, especially the one codified in IEEE 754.

like image 42
Wooble Avatar answered Sep 22 '22 14:09

Wooble