Convertir fracción decimal a número binario

Dado un número decimal de fracción n y un entero k, convierta el número decimal n en un número binario equivalente con una precisión de hasta k después del punto decimal. 

Ejemplos: 

Input: n = 2.47, k = 5
Output: 10.01111

Input: n = 6.986 k = 8
Output: 110.11111100
Le recomendamos encarecidamente que haga clic aquí y lo practique antes de pasar a la solución.

A) Convertir la parte integral de decimal a equivalente binario 

  1. Divide el número decimal por 2 y almacena los restos en una array. 
  2. Divide el cociente entre 2. 
  3. Repite el paso 2 hasta que obtengamos el cociente igual a cero.
  4. El número binario equivalente sería el reverso de todos los restos del paso 1.

B) Convertir la parte fraccionaria de decimal a equivalente binario 

  1. Multiplica el número decimal fraccionario por 2. 
  2. La parte integral del número decimal resultante será el primer dígito del número binario de fracción. 
  3. Repita el paso 1 usando solo la parte fraccionaria del número decimal y luego el paso 2. 

C) Combinar tanto la parte integral como la fraccionaria del número binario.

Ilustración  :

Let's take an example for n = 4.47 k = 3

Step 1: Conversion of 4 to binary
1. 4/2 : Remainder = 0 : Quotient = 2
2. 2/2 : Remainder = 0 : Quotient = 1
3. 1/2 : Remainder = 1 : Quotient = 0

So equivalent binary of integral part of decimal is 100.

Step 2: Conversion of .47 to binary
1. 0.47 * 2 = 0.94, Integral part: 0
2. 0.94 * 2 = 1.88, Integral part: 1
3. 0.88 * 2 = 1.76, Integral part: 1

So equivalent binary of fractional part of decimal is .011

Step 3: Combined the result of step 1 and 2.

Final answer can be written as:
100 + .011 = 100.011

Programa para demostrar los pasos anteriores: 

C++

// C++ program to convert fractional decimal
// to binary number
#include<bits/stdc++.h>
using namespace std;
 
// Function to convert decimal to binary upto
// k-precision after decimal point
string decimalToBinary(double num, int k_prec)
{
    string binary = "";
 
    // Fetch the integral part of decimal number
    int Integral = num;
 
    // Fetch the fractional part decimal number
    double fractional = num - Integral;
 
    // Conversion of integral part to
    // binary equivalent
    while (Integral)
    {
        int rem = Integral % 2;
 
        // Append 0 in binary
        binary.push_back(rem +'0');
 
        Integral /= 2;
    }
 
    // Reverse string to get original binary
    // equivalent
    reverse(binary.begin(),binary.end());
 
    // Append point before conversion of
    // fractional part
    binary.push_back('.');
 
    // Conversion of fractional part to
    // binary equivalent
    while (k_prec--)
    {
        // Find next bit in fraction
        fractional *= 2;
        int fract_bit = fractional;
 
        if (fract_bit == 1)
        {
            fractional -= fract_bit;
            binary.push_back(1 + '0');
        }
        else
            binary.push_back(0 + '0');
    }
 
    return binary;
}
 
// Driver code
int main()
{
 
    double n = 4.47;
    int k = 3;
    cout << decimalToBinary(n, k) << "\n";
 
    n = 6.986 , k = 5;
    cout << decimalToBinary(n, k);
    return 0;
}

Java

// Java program to convert fractional decimal
// to binary number
import java.util.*;
 
class GFG
{
 
    // Function to convert decimal to binary upto
    // k-precision after decimal point
    static String decimalToBinary(double num, int k_prec)
    {
        String binary = "";
 
        // Fetch the integral part of decimal number
        int Integral = (int) num;
 
        // Fetch the fractional part decimal number
        double fractional = num - Integral;
 
        // Conversion of integral part to
        // binary equivalent
        while (Integral > 0)
        {
            int rem = Integral % 2;
 
            // Append 0 in binary
            binary += ((char)(rem + '0'));
 
            Integral /= 2;
        }
 
        // Reverse string to get original binary
        // equivalent
        binary = reverse(binary);
 
        // Append point before conversion of
        // fractional part
        binary += ('.');
 
        // Conversion of fractional part to
        // binary equivalent
        while (k_prec-- > 0)
        {
            // Find next bit in fraction
            fractional *= 2;
            int fract_bit = (int) fractional;
 
            if (fract_bit == 1)
            {
                fractional -= fract_bit;
                binary += (char)(1 + '0');
            }
            else
            {
                binary += (char)(0 + '0');
            }
        }
 
        return binary;
    }
 
    static String reverse(String input)
    {
        char[] temparray = input.toCharArray();
        int left, right = 0;
        right = temparray.length - 1;
 
        for (left = 0; left < right; left++, right--)
        {
            // Swap values of left and right
            char temp = temparray[left];
            temparray[left] = temparray[right];
            temparray[right] = temp;
        }
        return String.valueOf(temparray);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        double n = 4.47;
        int k = 3;
        System.out.println(decimalToBinary(n, k));
 
        n = 6.986;
        k = 5;
        System.out.println(decimalToBinary(n, k));
    }
}
 
// This code contributed by Rajput-Ji

Python3

# Python3 program to convert fractional
# decimal to binary number
 
# Function to convert decimal to binary
# upto k-precision after decimal point
def decimalToBinary(num, k_prec) :
 
    binary = ""
 
    # Fetch the integral part of
    # decimal number
    Integral = int(num)
 
    # Fetch the fractional part
    # decimal number
    fractional = num - Integral
 
    # Conversion of integral part to
    # binary equivalent
    while (Integral) :
         
        rem = Integral % 2
 
        # Append 0 in binary
        binary += str(rem);
 
        Integral //= 2
     
    # Reverse string to get original
    # binary equivalent
    binary = binary[ : : -1]
 
    # Append point before conversion
    # of fractional part
    binary += '.'
 
    # Conversion of fractional part
    # to binary equivalent
    while (k_prec) :
         
        # Find next bit in fraction
        fractional *= 2
        fract_bit = int(fractional)
 
        if (fract_bit == 1) :
             
            fractional -= fract_bit
            binary += '1'
             
        else :
            binary += '0'
 
        k_prec -= 1
 
    return binary
 
# Driver code
if __name__ == "__main__" :
     
    n = 4.47
    k = 3
    print(decimalToBinary(n, k))
 
    n = 6.986
    k = 5
    print(decimalToBinary(n, k))
 
# This code is contributed by Ryuga

C#

// C# program to convert fractional decimal
// to binary number
using System;
 
class GFG
{
  
    // Function to convert decimal to binary upto
    // k-precision after decimal point
    static String decimalToBinary(double num, int k_prec)
    {
        String binary = "";
  
        // Fetch the integral part of decimal number
        int Integral = (int) num;
  
        // Fetch the fractional part decimal number
        double fractional = num - Integral;
  
        // Conversion of integral part to
        // binary equivalent
        while (Integral > 0)
        {
            int rem = Integral % 2;
  
            // Append 0 in binary
            binary += ((char)(rem + '0'));
  
            Integral /= 2;
        }
  
        // Reverse string to get original binary
        // equivalent
        binary = reverse(binary);
  
        // Append point before conversion of
        // fractional part
        binary += ('.');
  
        // Conversion of fractional part to
        // binary equivalent
        while (k_prec-- > 0)
        {
            // Find next bit in fraction
            fractional *= 2;
            int fract_bit = (int) fractional;
  
            if (fract_bit == 1)
            {
                fractional -= fract_bit;
                binary += (char)(1 + '0');
            }
            else
            {
                binary += (char)(0 + '0');
            }
        }
  
        return binary;
    }
  
    static String reverse(String input)
    {
        char[] temparray = input.ToCharArray();
        int left, right = 0;
        right = temparray.Length - 1;
  
        for (left = 0; left < right; left++, right--)
        {
            // Swap values of left and right
            char temp = temparray[left];
            temparray[left] = temparray[right];
            temparray[right] = temp;
        }
        return String.Join("",temparray);
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        double n = 4.47;
        int k = 3;
        Console.WriteLine(decimalToBinary(n, k));
  
        n = 6.986;
        k = 5;
        Console.WriteLine(decimalToBinary(n, k));
    }
}
 
// This code has been contributed by 29AjayKumar

PHP

<?php
// PHP program to convert fractional decimal
// to binary number
 
// Function to convert decimal to binary upto
// k-precision after decimal point
function decimalToBinary($num, $k_prec)
{
    $binary = "";
 
    // Fetch the integral part of decimal number
    $Integral = (int)($num);
 
    // Fetch the fractional part decimal number
    $fractional = $num - $Integral;
 
    // Conversion of integral part to
    // binary equivalent
    while ($Integral)
    {
        $rem = $Integral % 2;
 
        // Append 0 in binary
        $binary.=chr($rem + 48 );
 
        $Integral = (int)($Integral/2);
    }
 
    // Reverse string to get original binary
    // equivalent
    $binary=strrev($binary);
 
    // Append point before conversion of
    // fractional part
    $binary.='.';
 
    // Conversion of fractional part to
    // binary equivalent
    while ($k_prec--)
    {
        // Find next bit in fraction
        $fractional *= 2;
        $fract_bit = (int)$fractional;
 
        if ($fract_bit == 1)
        {
            $fractional -= $fract_bit;
            $binary.=chr(1 + 48 );
        }
        else
            $binary.=chr(0 + 48 );
    }
 
    return $binary;
}
 
// Driver code
 
    $n = 4.47;
    $k = 3;
    echo decimalToBinary($n, $k)."\n";
 
    $n = 6.986;
    $k = 5;
    echo decimalToBinary($n, $k);
     
// This code is contributed by mits
?>

Javascript

<script>
 
    // JavaScript program to convert fractional
    // decimal to binary number
     
    // Function to convert decimal to binary upto
    // k-precision after decimal point
    function decimalToBinary(num, k_prec)
    {
        let binary = "";
    
        // Fetch the integral part of decimal number
        let Integral = parseInt(num, 10);
    
        // Fetch the fractional part decimal number
        let fractional = num - Integral;
    
        // Conversion of integral part to
        // binary equivalent
        while (Integral > 0)
        {
            let rem = Integral % 2;
    
            // Append 0 in binary
            binary +=
            (String.fromCharCode(rem + '0'.charCodeAt()));
    
            Integral = parseInt(Integral / 2, 10);
        }
    
        // Reverse string to get original binary
        // equivalent
        binary = reverse(binary);
    
        // Append point before conversion of
        // fractional part
        binary += ('.');
    
        // Conversion of fractional part to
        // binary equivalent
        while (k_prec-- > 0)
        {
            // Find next bit in fraction
            fractional *= 2;
            let fract_bit = parseInt(fractional, 10);
    
            if (fract_bit == 1)
            {
                fractional -= fract_bit;
                binary +=
                String.fromCharCode(1 + '0'.charCodeAt());
            }
            else
            {
                binary +=
                String.fromCharCode(0 + '0'.charCodeAt());
            }
        }
    
        return binary;
    }
    
    function reverse(input)
    {
        let temparray = input.split('');
        let left, right = 0;
        right = temparray.length - 1;
    
        for (left = 0; left < right; left++, right--)
        {
            // Swap values of left and right
            let temp = temparray[left];
            temparray[left] = temparray[right];
            temparray[right] = temp;
        }
        return temparray.join("");
    }
     
    let n = 4.47;
    let k = 3;
    document.write(decimalToBinary(n, k) + "</br>");
 
    n = 6.986;
    k = 5;
    document.write(decimalToBinary(n, k));
     
</script>
Producción

100.011
110.11111

Complejidad temporal: O(len(n)) 
Espacio auxiliar: O(len(n)) 

donde len() es el total de dígitos contenidos en el número n.
Convertir fracción binaria a decimal

Este artículo es una contribución de Shubham Bansal . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a contribuido@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *