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++
#include <bits/stdc++.h>
using namespace std;
void HexaDecimaltoBCD(string s)
{
int len = s.length(), check = 0;
int num = 0, sum = 0, mul = 1;
for ( int i = 0; i <= len - 1; i++) {
if (s[i] >= 47 && s[i] <= 52)
cout << bitset<4>(s[i])
<< " " ;
else
cout << bitset<4>(s[i] - 55)
<< " " ;
}
}
int main()
{
string s = "11F" ;
HexaDecimaltoBCD(s);
return 0;
}
|
Java
public class Main
{
public static void HexaDecimaltoBCD(String s)
{
int len = s.length(), check = 0 ;
int num = 0 , sum = 0 , mul = 1 ;
for ( int i = 0 ; i <= len - 1 ; i++) {
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" ;
HexaDecimaltoBCD(s);
}
}
|
Python3
def HexaDecimaltoBCD( str ):
for i in range ( len ( str )):
print ( "{0:04b}" . format (
int ( str [i], 16 )), end = " " )
str = "11F"
HexaDecimaltoBCD( str )
|
C#
using System;
class GFG {
static void HexaDecimaltoBCD( string s)
{
int len = s.Length;
for ( int i = 0; i <= len - 1; i++) {
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" ;
HexaDecimaltoBCD(s);
}
}
|
Javascript
function HexaDecimaltoBCD(s)
{
var len = s.length;
var check = 0;
var num = 0;
var sum = 0;
var mul = 1;
for ( var i = 0; i < len; i++) {
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) + " " );
}
}
}
var s = "11F" ;
HexaDecimaltoBCD(s);
|
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 {
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 bcd;
}
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);
|
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.
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;
}
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
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
{
static string HexToBcd( string hexNum)
{
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 = "" ;
foreach ( char c in hexNum)
{
bcd += lookup;
}
return bcd;
}
static void Main()
{
string hexNum = "2A" ;
string bcdNum = HexToBcd(hexNum);
Console.WriteLine( "Hexadecimal number: " + hexNum);
Console.WriteLine( "BCD number: " + bcdNum);
}
}
|
Javascript
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 hex_to_bcd(hex_num) {
let bcd = "" ;
for (let c of hex_num) {
bcd += lookup;
}
return bcd;
}
const hex_num = "2A" ;
const 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
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!