Open In App

Program to convert Hexa-Decimal Number to its equivalent BCD

Given a HexaDecimal Number N, the task is to convert the number to its equivalent Binary Coded Decimal.
Examples: 

Input: 11F 
Output: 0001 0001 1111 
Explanation: 
Binary of 1 – 0001 
Binary of F – 1111 
Thus, Equivalent BCD is 0001 0001 1111
Input: A D 
Output: 1010 1101 
Explanation: 
Binary of A – 1010 
Binary of D – 1101 
Thus, Equivalent BCD is 1010 1101 



Approach: The idea is to iterate over each digit of the given Hexa-Decimal number and find the four digit Binary Equivalent of that digit. Finally, print all the converted digits one by one.
Below is the implementation of the above approach: 




// C++ implementation  to convert the given
// HexaDecimal number to its equivalent BCD.
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to convert
// HexaDecimal to its BCD
void HexaDecimaltoBCD(string s)
{
    int len = s.length(), check = 0;
    int num = 0, sum = 0, mul = 1;
 
    // Iterating through the digits
    for (int i = 0; i <= len - 1; i++) {
 
        // check whether s[i] is a character
        // or a integer between 0 to 9
        // and compute its equivalent BCD
        if (s[i] >= 47 && s[i] <= 52)
            cout << bitset<4>(s[i])
                 << " ";
        else
            cout << bitset<4>(s[i] - 55)
                 << " ";
    }
}
 
// Driver Code
int main()
{
    string s = "11F";
 
    // Function Call
    HexaDecimaltoBCD(s);
 
    return 0;
}




// Java implementation  to convert the given
// HexaDecimal number to its equivalent BCD.
public class Main
{
    // Function to convert
    // HexaDecimal to its BCD
    public static void HexaDecimaltoBCD(String s)
    {
        int len = s.length(), check = 0;
        int num = 0, sum = 0, mul = 1;
       
        // Iterating through the digits
        for (int i = 0; i <= len - 1; i++) {
       
            // check whether s[i] is a character
            // or a integer between 0 to 9
            // and compute its equivalent BCD
            if (s.charAt(i) >= 47 && s.charAt(i) <= 52)
            {
                String result = Integer.toBinaryString((int)s.charAt(i));
                System.out.print(result.substring(result.length() - 4) + " ");
            }
            else
            {
                String result = Integer.toBinaryString((int)s.charAt(i) - 55);
                System.out.print(result.substring(result.length() - 4) + " ");
            }
        }
    }
 
    public static void main(String[] args) {
        String s = "11F";
   
        // Function Call
        HexaDecimaltoBCD(s);
    }
}
 
// This code is contributed by divyesh072019




# Python3 program to convert the given
# HexaDecimal number to its equivalent BCD
 
# Function to convert
# Haxadecimal to BCD
def HexaDecimaltoBCD(str):
 
    # Iterating through the digits
    for i in range(len(str)):
         
        # Conversion into equivalent BCD
        print("{0:04b}".format(
              int(str[i], 16)), end = " ")
 
# Driver code
str = "11F"
 
# Function call
HexaDecimaltoBCD(str)
 
# This code is contributed by himanshu77




// C# implementation  to convert the given
// HexaDecimal number to its equivalent BCD.
using System;
class GFG {
     
    // Function to convert
    // HexaDecimal to its BCD
    static void HexaDecimaltoBCD(string s)
    {
        int len = s.Length;
        
        // Iterating through the digits
        for (int i = 0; i <= len - 1; i++) {
        
            // check whether s[i] is a character
            // or a integer between 0 to 9
            // and compute its equivalent BCD
            if (s[i] >= 47 && s[i] <= 52)
            {
                string result = Convert.ToString((int)s[i], 2);
                Console.Write(result.Substring(result.Length - 4) + " ");
            }
            else
            {
                string result = Convert.ToString((int)s[i] - 55, 2);
                Console.Write(result.Substring(result.Length - 4) + " ");
            }
        }
    }
     
  static void Main() {
        string s = "11F";
    
        // Function Call
        HexaDecimaltoBCD(s);
  }
}
 
// This code is contributed by diyeshrabadiya07




// JavaScript implementation  to convert the given
// HexaDecimal number to its equivalent BCD.
 
// Function to convert
// HexaDecimal to its BCD
function HexaDecimaltoBCD(s)
{
    var len = s.length;
    var check = 0;
    var num = 0;
    var sum = 0;
    var mul = 1;
 
    // Iterating through the digits
    for (var i = 0; i < len; i++) {
 
        // check whether s[i] is a character
        // or a integer between 0 to 9
        // and compute its equivalent BCD
        if (s[i] >= '0' && s[i] <= '9') {
            var result
                = parseInt(s[i]).toString(2).padStart(4,
                                                      "0");
            process.stdout.write(result.substr(-4) + " ");
        }
        else {
            var result = (s[i].charCodeAt() - 55)
                             .toString(2)
                             .padStart(4, "0");
            process.stdout.write(result.substr(-4) + " ");
        }
    }
}
 
// Driver Code
var s = "11F";
 
// Function Call
HexaDecimaltoBCD(s);
 
// This code is contributed by phasing17

Output

0001 0001 1111







Method 2: 

1. Initialize an empty string variable bcd to store the binary coded decimal representation.
2. Iterate through each character in the input hexadecimal number using a for loop.
3. Convert the character to its equivalent integer value using the int() function with base 16.
4. Convert the integer value to its binary representation using the bin() function, which returns a string of binary digits prefixed with “0b”.
5. Remove the “0b” prefix from the binary string using string slicing ([2:]).
6. Ensure that the binary string has 4 digits by zero-padding it using the zfill() method.
7. Append the zero-padded binary string to the bcd variable.
8. After iterating through all characters in the input hexadecimal number, return the final bcd string.




#include <bitset>
#include <iostream>
#include <string>
 
using namespace std;
 
string hex_to_bcd(string hex_num)
{
    string bcd = "";
    for (char c : hex_num) {
        bcd += bitset<4>(stoi(string(1, c), nullptr, 16))
                   .to_string();
    }
    return bcd;
}
 
int main()
{
    string hex_num = "2A";
    string bcd_num = hex_to_bcd(hex_num);
    cout << "Hexadecimal number: " << hex_num << endl;
    cout << "BCD number: " << bcd_num << endl;
    return 0;
}




import java.util.*;
 
public class HexToBCD {
    public static String hexToBCD(String hexNum)
    {
        String bcd = "";
        for (int i = 0; i < hexNum.length(); i++) {
            char c = hexNum.charAt(i);
            int num = Character.digit(c, 16);
            String bits = String.format(
                "%04d", Integer.parseInt(
                            Integer.toBinaryString(num)));
            bcd += bits;
        }
        return bcd;
    }
    public static void main(String[] args)
    {
        String hexNum = "2A";
        String bcdNum = hexToBCD(hexNum);
        System.out.println("Hexadecimal number: " + hexNum);
        System.out.println("BCD number: " + bcdNum);
    }
}




def hex_to_bcd(hex_num):
    bcd = ""
    for char in hex_num:
        bcd += bin(int(char, 16))[2:].zfill(4)
    return bcd
 
hex_num = "2A"
bcd_num = hex_to_bcd(hex_num)
print("Hexadecimal number:", hex_num)
print("BCD number:", bcd_num)




using System;
 
class Program {
 
    // Function to convert HEX to BCD
    static string HexToBcd(string hexNum)
    {
        string bcd = "";
        foreach(char c in hexNum)
        {
            bcd += Convert
                       .ToString(Convert.ToInt32(
                                     c.ToString(), 16),
                                 2)
                       .PadLeft(4, '0');
        }
 
        // Return the BCD
        return bcd;
    }
 
    // Driver Code
    static void Main(string[] args)
    {
        string hexNum = "2A";
        string bcdNum = HexToBcd(hexNum);
        Console.WriteLine("Hexadecimal number: {0}",
                          hexNum);
        Console.WriteLine("BCD number: {0}", bcdNum);
    }
}




function hex_to_bcd(hex_num) {
    let bcd = "";
    for (let c of hex_num) {
        bcd += parseInt(c, 16).toString(2).padStart(4, '0');
    }
    return bcd;
}
 
let hex_num = "2A";
let bcd_num = hex_to_bcd(hex_num);
console.log("Hexadecimal number: " + hex_num);
console.log("BCD number: " + bcd_num);

Output
Hexadecimal number: 2A
BCD number: 00101010







Time complexity: 

The time complexity of the hex_to_bcd function is O(n), where n is the length of the input hexadecimal string. This is because the function iterates through each character in the string and performs a constant amount of work for each character.

Auxiliary Space: 

The space auxiliary complexity of the function is also O(n), since it creates a new string variable bcd to store the binary coded decimal representation of the input hexadecimal number, which can be as long as 2n digits (since each hexadecimal digit corresponds to 4 binary digits in BCD representation). 

Method: Using look up table method

First, the program defines an unordered map named lookup which maps each hexadecimal character to its BCD representation. For example, the hexadecimal character ‘0’ maps to “0000” and the character ‘A’ maps to “1010”.

Then, the hex_to_bcd function takes a hexadecimal number as a string and initializes an empty string bcd to store the BCD representation. The function iterates over each character in the input string using a range-based for loop. For each character, it looks up its corresponding BCD representation in the lookup map and appends it to the bcd string.

Finally, the main function calls hex_to_bcd with an example hexadecimal number “2A” and stores the result in bcd_num. It then prints both the original hexadecimal number and the resulting BCD number to the console.




#include <iostream>
#include <string>
#include <unordered_map>
 
using namespace std;
 
string hex_to_bcd(string hex_num)
{
    unordered_map<char, string> lookup {
        {'0', "0000"}, {'1', "0001"}, {'2', "0010"}, {'3', "0011"},
        {'4', "0100"}, {'5', "0101"}, {'6', "0110"}, {'7', "0111"},
        {'8', "1000"}, {'9', "1001"}, {'A', "1010"}, {'B', "1011"},
        {'C', "1100"}, {'D', "1101"}, {'E', "1110"}, {'F', "1111"}
    };
 
    string bcd = "";
    for (char c : hex_num) {
        bcd += lookup;
    }
    return bcd;
}
 
int main()
{
    string hex_num = "2A";
    string bcd_num = hex_to_bcd(hex_num);
    cout << "Hexadecimal number: " << hex_num << endl;
    cout << "BCD number: " << bcd_num << endl;
    return 0;
}




import java.util.HashMap;
 
public class HexToBCD {
    public static String hexToBCD(String hexNum) {
        HashMap<Character, String> lookup = new HashMap<>();
        lookup.put('0', "0000");
        lookup.put('1', "0001");
        lookup.put('2', "0010");
        lookup.put('3', "0011");
        lookup.put('4', "0100");
        lookup.put('5', "0101");
        lookup.put('6', "0110");
        lookup.put('7', "0111");
        lookup.put('8', "1000");
        lookup.put('9', "1001");
        lookup.put('A', "1010");
        lookup.put('B', "1011");
        lookup.put('C', "1100");
        lookup.put('D', "1101");
        lookup.put('E', "1110");
        lookup.put('F', "1111");
 
        StringBuilder bcd = new StringBuilder();
        for (char c : hexNum.toCharArray()) {
            bcd.append(lookup.get(c));
        }
        return bcd.toString();
    }
 
    public static void main(String[] args) {
        String hexNum = "2A";
        String bcdNum = hexToBCD(hexNum);
        System.out.println("Hexadecimal number: " + hexNum);
        System.out.println("BCD number: " + bcdNum);
    }
}




def hex_to_bcd(hex_num):
    lookup = {
        '0': "0000", '1': "0001", '2': "0010", '3': "0011",
        '4': "0100", '5': "0101", '6': "0110", '7': "0111",
        '8': "1000", '9': "1001", 'A': "1010", 'B': "1011",
        'C': "1100", 'D': "1101", 'E': "1110", 'F': "1111"
    }
 
    bcd = ""
    for c in hex_num:
        bcd += lookup
    return bcd
 
hex_num = "2A"
bcd_num = hex_to_bcd(hex_num)
print("Hexadecimal number:", hex_num)
print("BCD number:", bcd_num)




using System;
using System.Collections.Generic;
 
class GFG
{
    // Function to convert a hexadecimal number to its BCD representation
    static string HexToBcd(string hexNum)
    {
        // Define a dictionary to map each hexadecimal digit to its corresponding BCD representation.
        Dictionary<char, string> lookup = new Dictionary<char, string> {
            {'0', "0000"}, {'1', "0001"}, {'2', "0010"}, {'3', "0011"},
            {'4', "0100"}, {'5', "0101"}, {'6', "0110"}, {'7', "0111"},
            {'8', "1000"}, {'9', "1001"}, {'A', "1010"}, {'B', "1011"},
            {'C', "1100"}, {'D', "1101"}, {'E', "1110"}, {'F', "1111"}
        };
 
        string bcd = "";
        // Iterate through each character in the hexadecimal number.
        foreach (char c in hexNum)
        {
            // Convert each hexadecimal digit to its BCD representation and append it to the result.
            bcd += lookup;
        }
        return bcd;
    }
 
    static void Main()
    {
        string hexNum = "2A";
        // Call the HexToBcd function to convert the hexadecimal number to its BCD representation.
        string bcdNum = HexToBcd(hexNum);
 
        // Display the original hexadecimal number and its BCD representation.
        Console.WriteLine("Hexadecimal number: " + hexNum);
        Console.WriteLine("BCD number: " + bcdNum);
    }
}




// Define a dictionary to map each hexadecimal digit to its corresponding BCD representation.
const lookup = {
    '0': "0000", '1': "0001", '2': "0010", '3': "0011",
    '4': "0100", '5': "0101", '6': "0110", '7': "0111",
    '8': "1000", '9': "1001", 'A': "1010", 'B': "1011",
    'C': "1100", 'D': "1101", 'E': "1110", 'F': "1111"
};
 
// Function to convert a hexadecimal number to its BCD representation
function hex_to_bcd(hex_num) {
    let bcd = "";
     
    // Iterate through each character in the hexadecimal number.
    for (let c of hex_num) {
         
        // Convert each hexadecimal digit to its BCD representation and append it to the result.
        bcd += lookup;
    }
    return bcd;
}
 
const hex_num = "2A";
 
// Call the HexToBcd function to convert the hexadecimal number to its BCD representation.
const bcd_num = hex_to_bcd(hex_num);
 
// Display the original hexadecimal number and its BCD representation.
console.log("Hexadecimal number: " + hex_num);
console.log("BCD number: " + bcd_num);

Output
Hexadecimal number: 2A
BCD number: 00101010








The time complexity of this algorithm is O(n), where n is the length of the input hex_num.

The auxiliary space complexity is also O(n), since we need to store the BCD representation as a string.


Article Tags :