views:

74

answers:

3

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?

+2  A: 

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.)

Bill K
+1  A: 

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.

Wooble
+2  A: 

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.

Rick Regan
That's a cute trick--I've never seen it. Doesn't really teach you what is going on--I wonder how that translates to other bases... I'm gonna go try me some octal.
Bill K
@ Bill K: It works for any base! For octal, for example, just replace 2 with 8 (0.8125 converts to 0.64 base 8).
Rick Regan