Program to convert Hexa-Decimal Number to its equivalent BCD
Last Updated :
20 Sep, 2023
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++
// 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
// 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
# 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#
// 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
// 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
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.
C++
#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;
}
Java
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);
}
}
Python3
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)
C#
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);
}
}
JavaScript
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);
OutputHexadecimal 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.
C++
#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[c];
}
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;
}
Java
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);
}
}
Python3
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[c]
return bcd
hex_num = "2A"
bcd_num = hex_to_bcd(hex_num)
print("Hexadecimal number:", hex_num)
print("BCD number:", bcd_num)
C#
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[c];
}
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);
}
}
JavaScript
// 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[c];
}
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);
OutputHexadecimal 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.
Similar Reads
Program to Convert BCD number into Decimal number
Given a BCD (Binary Coded Decimal) number, the task is to convert the BCD number into its equivalent Decimal number. Examples: Input: BCD = 100000101000 Output: 828 Explanation: Dividing the number into chunks of 4, it becomes 1000 0010 1000. Here, 1000 is equivalent to 8 and 0010 is equivalent to 2
10 min read
Convert a given Decimal number to its BCD representation
Given a decimal number N, the task is to convert N to it's Binary Coded Decimal(BCD) form.Examples: Input: N = 12 Output: 0001 0010 Explanation: Considering 4-bit concept: 1 in binary is 0001 and 2 in binary is 0010. So it's equivalent BCD is 0001 0010. Input: N = 10 Output: 0001 0000 Explanation: C
5 min read
Program to convert a Binary Number to Hexa-Decimal Number
Given a Binary Number, the task is to convert this Binary number to its equivalent Hexa-Decimal Number.Examples: Input: 100000101111 Output: 82F Explanation: Dividing the number into chunks of 4, it becomes 1000 0010 1111. Here, 1000 is equivalent to 8, 0010 is equivalent to 2 and 1111 is equivalent
10 min read
Program to convert float decimal to Octal number
Write a program that converts a floating-point decimal number into its octal format. The program should take a number and the precision for the octal fractional part as inputs from the user. It should calculate and provide its correct octal representation as output. Examples: Input: Number = 123.45,
8 min read
Program to Convert Hexadecimal Number to Binary
Given a Hexadecimal number as an input, the task is to convert that number to a Binary number.Examples: Input: Hexadecimal = 1AC5 Output: Binary = 0001101011000101 Explanation: Equivalent binary value of 1: 0001 Equivalent binary value of A: 1010 Equivalent binary value of C: 1100 Equivalent binary
14 min read
Program to convert a binary number to hexadecimal number
Given a Binary Number, the task is to convert the given binary number to its equivalent hexadecimal number. The input could be very large and may not fit even into an unsigned long long int.Examples:Â Input: 110001110Output: 18EInput: 1111001010010100001.010110110011011Output: 794A1.5B36 794A1D9B App
13 min read
Program to Convert Hexadecimal to Octal
Given a Hexadecimal number, the task is to convert it into an Octal number.Examples: Input: Hexadecimal = 1AC Output: Binary = 0654 Explanation: Equivalent binary value of 1: 0001 Equivalent binary value of A: 1010 Equivalent binary value of C: 1100 Grouping in terms of 3: 000 110 101 100 Equivalent
15 min read
Decimal Equivalent of Gray Code and its Inverse
Given a decimal number n. Find the gray code of this number in decimal form. Examples: Input : 7 Output : 4 Explanation: 7 is represented as 111 in binary form. The equivalent gray code of 111 is 100 in binary form, whose decimal equivalent is 4. Input : 10 Output : 15 Explanation: 10 is represented
7 min read
Program for decimal to hexadecimal conversion
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent hexadecimal number. i.e. convert the number with base value 10 to base value 16.Hexadecimal numbers use 16 values to represent a number. Numbers from 0-9 are expressed by digits 0-9 and
8 min read
Convert Decimal to Other Bases in Python
Given a number in decimal number convert it into binary, octal and hexadecimal number. Here is function to convert decimal to binary, decimal to octal and decimal to hexadecimal. Examples: Input : 55 Output : 55 in Binary : 0b110111 55 in Octal : 0o67 55 in Hexadecimal : 0x37 Input : 282 Output : 28
2 min read