How to convert decimal (xx.xx) to binary

This is not necessarily a programming issue, but I'm sure you know how to do it. How to convert floating point numbers to binary.

The number I'm looking at is 27.625.

27 will be 11011, but what should I do with .625?

+4
source share
4 answers

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

You know that .1 in binary must be .5 in decimal, so a .1 value is .5 (1/2)

.01 costs .25 (1/4) (half the previous)

.001 worth (1/8) (half 1/4)

Notice how the denominator progresses in the same way as all numbers to the left of the decimal standard pattern ^ 2? The next one should be 1/16 ...

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

.1 binary with decimal remainder .125

Now you have the next place, it costs 0.25 deck, is it less than your current balance .125? No, so you don’t have enough decimal “Money” to buy second place, it should be 0

.10 binary, still .125 remainder.

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

+7
source

On paper, a good algorithm for converting the fractional part of a decimal is the algorithm of "repeated multiplication by 2" (for details see http://www.exploringbinary.com/base-conversion-in-php-using-bcmath/ , under the heading "dec2bin_f () "). For example, 0.8125 is converted 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 deleted and stored at each step, forming a binary result: 0.1101.

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

+11
source

There are several different ways to encode a non-integer in binary format. Today, the most common type is floating point representations, especially those encoded in IEEE 754 .

+2
source

the code works for me, as shown below, you can use this code to convert any dobule values:

  private static String doubleToBinaryString( double n ) { String val = Integer.toBinaryString((int)n)+"."; // Setting up string for result String newN ="0" + (""+n).substring((""+n).indexOf(".")); n = Double.parseDouble(newN); while ( n > 0 ) { // While the fraction is greater than zero (not equal or less than zero) double r = n * 2; // Multiply current fraction (n) by 2 if( r >= 1 ) { // If the ones-place digit >= 1 val += "1"; // Concat a "1" to the end of the result string (val) n = r - 1; // Remove the 1 from the current fraction (n) }else{ // If the ones-place digit == 0 val += "0"; // Concat a "0" to the end of the result string (val) n = r; // Set the current fraction (n) to the new fraction } } return val; // return the string result with all appended binary values } 
0
source

All Articles