Convierta el BCD dado a su forma binaria equivalente

Dado un BCD (decimal codificado en binario) , la tarea es convertirlo a su número binario equivalente . 
Ejemplos: 

Entrada: 1001000 
Salida: 110000 
Explicación: 
El valor entero del BCD dado es 48 (0100 -> 4, 1000 -> 8). 
(48) 10 = (110000) 2
Entrada: 1001001 
Salida: 110001 

Enfoque: para resolver este problema, necesitamos dividir el número BCD dado en fragmentos binarios de longitud 4 y convertirlos en enteros uno por uno para generar la representación entera final del BCD dado. Una vez generado, convierta el entero a su forma binaria.
A continuación se muestra la implementación del enfoque anterior.
 

C++

// C++ code to convert BCD to its
// equivalent Binary
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to convert BCD to Decimal
string bcdToBinary(string s)
{
    int l = s.length();
    int num = 0;
    int mul = 1;
    int sum = 0;
     
     // If the length of given BCD is not
    // divisible by 4
    for (int i = l % 4 - 1; i >= 0; i--)
    {
        sum += (s[i] - '0') * mul;
        mul *= 2;
    }
    num = sum;
    sum = 0;
    mul = pow(2, 3);
    int ctr = 0;
    for (int i = l % 4; i < l; i++)
    {
        ctr++;
        sum += (s[i] - '0') * mul;
        mul /= 2;
        if (ctr == 4) {
            num = num * 10 + sum;
            sum = 0;
            mul = pow(2, 3);
            ctr = 0;
        }
    }
 
    // Convert decimal to binary
    string ans = "";
    while (num > 0) {
        ans += (char)(num % 2 + '0');
        num /= 2;
    }
    reverse(ans.begin(), ans.end());
    return ans;
}
 
// Driver Code
int main()
{
    string s = "1001000";
 
    // Function Call
    cout << bcdToBinary(s);
    return 0;
}

Java

// Java code to convert BCD to its
// equivalent Binary
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to convert BCD to Decimal
static String bcdToBinary(String s)
{
    int l = s.length();
    int num = 0;
    int mul = 1;
    int sum = 0;
     
    // If the length of given BCD is not
    // divisible by 4
    for(int i = l % 4 - 1; i >= 0; i--)
    {
        sum += (s.charAt(i) - '0') * mul;
        mul *= 2;
    }
 
    num = sum;
    sum = 0;
    mul = (int)Math.pow(2, 3);
    int ctr = 0;
     
    for(int i = l % 4; i < l; i++)
    {
        ctr++;
        sum += (s.charAt(i) - '0') * mul;
        mul /= 2;
         
        if (ctr == 4)
        {
            num = num * 10 + sum;
            sum = 0;
            mul = (int)Math.pow(2, 3);
            ctr = 0;
        }
    }
     
    // Convert decimal to binary
    String ans = "";
    while (num > 0)
    {
        ans += (char)(num % 2 + '0');
        num /= 2;
    }
 
    StringBuilder ans1 = new StringBuilder();
 
    // Append a string into StringBuilder input1
    ans1.append(ans);
 
    // Reverse StringBuilder input1
    ans = ans1.reverse().toString();
 
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    String s = "1001000";
     
    // Function call
    System.out.println(bcdToBinary(s));
}
}
 
// This code is contributed by coder001

Python3

# Python3 code to convert
# BCD to its equivalent Binary
 
# Function to convert
# BCD to Decimal
def bcdToBinary(s):
 
    l = len(s)
    num = 0;
    mul = 1;
    sum = 0;
      
    # If the length of given
    # BCD is not divisible by 4   
    for i in range(l % 4 - 1,
                   -1, -1):   
        sum += (ord(s[i]) -
                ord('0')) * mul;
        mul *= 2;
     
    num = sum;
    sum = 0;
    mul = pow(2, 3);
    ctr = 0;
     
    for i in range(l % 4, l):   
        ctr += 1;
        sum += (ord(s[i]) -
                ord('0')) * mul;
        mul //= 2;
        if (ctr == 4):
            num = num * 10 + sum;
            sum = 0;
            mul = pow(2, 3);
            ctr = 0;       
  
    # Convert decimal to binary
    ans = "";
    while (num > 0):
        ans += (chr((num % 2) +
                ord('0')));
        num //= 2;
    ans = ans[:: -1]
     
    return ans;
 
# Driver code
if __name__ == "__main__":
     
    s = "1001000";
  
    # Function Call
    print(bcdToBinary(s));
 
# This code is contributed by rutvik_56

C#

// C# code to convert BCD to its
// equivalent Binary
using System;
using System.Text;
public class GFG{
      
// Function to convert BCD to Decimal
static String bcdToBinary(String s)
{
    int l = s.Length;
    int num = 0;
    int mul = 1;
    int sum = 0;
      
    // If the length of given BCD is not
    // divisible by 4
    for(int i = l % 4 - 1; i >= 0; i--)
    {
        sum += (s[i] - '0') * mul;
        mul *= 2;
    }
    num = sum;
    sum = 0;
    mul = (int)Math.Pow(2, 3);
    int ctr = 0;
    for(int i = l % 4; i < l; i++)
    {
        ctr++;
        sum += (s[i] - '0') * mul;
        mul /= 2;
        if (ctr == 4)
        {
            num = num * 10 + sum;
            sum = 0;
            mul = (int)Math.Pow(2, 3);
            ctr = 0;
        }
    }
      
    // Convert decimal to binary
    String ans = "";
    while (num > 0)
    {
        ans += (char)(num % 2 + '0');
        num /= 2;
    }
    StringBuilder ans1 = new StringBuilder();
  
    // Append a string into StringBuilder input1
    ans1.Append(ans);
  
    // Reverse StringBuilder input1
    ans = reverse(ans1.ToString());
    return ans;
}
static String reverse(String input)
{
        char[] a = input.ToCharArray();
        int l, r = a.Length - 1;
        for (l = 0; l < r; l++, r--)
        {
            char temp = a[l];
            a[l] = a[r];
            a[r] = temp;
        }
        return String.Join("",a);
    }
   
// Driver code
public static void Main(String[] args)
{
    String s = "1001000";
      
    // Function call
    Console.WriteLine(bcdToBinary(s));
}
}
 
// This code is contributed by shikhasingrajput

Javascript

<script>
// Javascript code to convert BCD to its
// equivalent Binary
 
// Function to convert BCD to Decimal
function bcdToBinary(s)
{
    let l = s.length;
    let num = 0;
    let mul = 1;
    let sum = 0;
 
    // If the length of given BCD is not
    // divisible by 4
    for (let i = l % 4 - 1; i >= 0; i--)
    {
        sum += (s[i].charCodeAt(0) - '0'.charCodeAt(0)) * mul;
        mul *= 2;
    }
    num = sum;
    sum = 0;
    mul = Math.pow(2, 3);
    let ctr = 0;
    for (let i = l % 4; i < l; i++) {
        ctr++;
        sum += (s[i].charCodeAt(0) - '0'.charCodeAt(0)) * mul;
        mul = Math.floor(mul / 2);
        if (ctr == 4) {
            num = num * 10 + sum;
            sum = 0;
            mul = Math.pow(2, 3);
            ctr = 0;
        }
    }
 
    // Convert decimal to binary
    let ans = "";
    while (num > 0) {
        ans += String.fromCharCode(num % 2 + '0'.charCodeAt(0));
        num = Math.floor(num / 2);
    }
    ans = ans.split("").reverse().join("")
    console.log(ans)
    return ans;
}
 
// Driver Code
let s = "1001000";
 
// Function Call
document.write(bcdToBinary(s));
 
// This code is contributed by _saurabh_jaiswal
</script>
Producción: 

110000

 

Complejidad de tiempo: O(N) donde N denota la longitud de la string BCD proporcionada 
Espacio auxiliar: O(1)

Publicación traducida automáticamente

Artículo escrito por yashbeersingh42 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 *