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 to F
Therefore, the number becomes 82F
Input:10101101
Output:AD
Explanation:
Dividing the number into chunks of 4, it becomes 1010 1101.
Here, 1010 is equivalent to A and
1101 is equivalent to D.
Therefore, the number becomes AD.
Approach:
- Divide the given Binary number into chunks of 4, and start computing its equivalent HexaDecimal form.
- Store this number formed in a vector.
- Repeat the process for all the digits of the given Binary number.
- Print the numbers stored in the vector in reverse order.
Below is the implementation of the above approach:
// C++ code to convert Binary to its
// HexaDecimal number(base 16).
// Including Header Files
#include <bits/stdc++.h>
using namespace std;
// Function to convert
// Binary to HexaDecimal
void bToHexaDecimal(string s)
{
int len = s.length(), check = 0;
int num = 0, sum = 0, mul = 1;
vector<char> ans;
// Iterating through
// the bits backwards
for (int i = len - 1; i >= 0; i--) {
sum += (s[i] - '0') * mul;
mul *= 2;
check++;
// Computing the HexaDecimal
// Number formed so far
// and storing it in a vector.
if (check == 4 || i == 0) {
if (sum <= 9)
ans.push_back(sum + '0');
else
ans.push_back(sum + 55);
// Reinitializing all
// variables for next group.
check = 0;
sum = 0;
mul = 1;
}
}
len = ans.size();
// Printing the Hexadecimal
// number formed so far.
for (int i = len - 1; i >= 0; i--)
cout << ans[i];
}
// Driver Code
int main()
{
string s = "100000101111";
// Function Call
bToHexaDecimal(s);
return 0;
}
// Java code to convert BCD to its
// HexaDecimal number(base 16).
// Including Header Files
import java.util.*;
class GFG{
// Function to convert
// BCD to HexaDecimal
static void bcdToHexaDecimal(char []s)
{
int len = s.length, check = 0;
int num = 0, sum = 0, mul = 1;
Vector<Character> ans =
new Vector<Character>();
// Iterating through
// the bits backwards
for (int i = len - 1; i >= 0; i--)
{
sum += (s[i] - '0') * mul;
mul *= 2;
check++;
// Computing the HexaDecimal
// Number formed so far
// and storing it in a vector.
if (check == 4 || i == 0)
{
if (sum <= 9)
ans.add((char) (sum + '0'));
else
ans.add((char) (sum + 55));
// Reinitializing all
// variables for next group.
check = 0;
sum = 0;
mul = 1;
}
}
len = ans.size();
// Printing the Hexadecimal
// number formed so far.
for (int i = len - 1; i >= 0; i--)
System.out.print(ans.get(i));
}
// Driver Code
public static void main(String[] args)
{
String s = "100000101111";
// Function Call
bcdToHexaDecimal(s.toCharArray());
}
}
// This code is contributed by Princi Singh
# Python3 code to convert BCD to its
# hexadecimal number(base 16).
# Function to convert BCD to hexadecimal
def bcdToHexaDecimal(s):
len1 = len(s)
check = 0
num = 0
sum = 0
mul = 1
ans = []
# Iterating through the bits backwards
i = len1 - 1
while(i >= 0):
sum += (ord(s[i]) - ord('0')) * mul
mul *= 2
check += 1
# Computing the hexadecimal number formed
# so far and storing it in a vector.
if (check == 4 or i == 0):
if (sum <= 9):
ans.append(chr(sum + ord('0')))
else:
ans.append(chr(sum + 55));
# Reinitializing all variables
# for next group.
check = 0
sum = 0
mul = 1
i -= 1
len1 = len(ans)
# Printing the hexadecimal
# number formed so far.
i = len1 - 1
while(i >= 0):
print(ans[i], end = "")
i -= 1
# Driver Code
if __name__ == '__main__':
s = "100000101111"
# Function Call
bcdToHexaDecimal(s)
# This code is contributed by Samarth
// C# code to convert BCD to its
// HexaDecimal number(base 16).
// Including Header Files
using System;
using System.Collections.Generic;
class GFG{
// Function to convert
// BCD to HexaDecimal
static void bcdToHexaDecimal(char []s)
{
int len = s.Length, check = 0;
int num = 0, sum = 0, mul = 1;
List<char> ans =
new List<char>();
// Iterating through
// the bits backwards
for (int i = len - 1; i >= 0; i--)
{
sum += (s[i] - '0') * mul;
mul *= 2;
check++;
// Computing the HexaDecimal
// Number formed so far
// and storing it in a vector.
if (check == 4 || i == 0)
{
if (sum <= 9)
ans.Add((char) (sum + '0'));
else
ans.Add((char) (sum + 55));
// Reinitializing all
// variables for next group.
check = 0;
sum = 0;
mul = 1;
}
}
len = ans.Count;
// Printing the Hexadecimal
// number formed so far.
for (int i = len - 1; i >= 0; i--)
Console.Write(ans[i]);
}
// Driver Code
public static void Main(String[] args)
{
String s = "100000101111";
// Function Call
bcdToHexaDecimal(s.ToCharArray());
}
}
// This code is contributed by 29AjayKumar
<script>
// Javascript code to convert Binary to its
// HexaDecimal number(base 16).
// Including Header Files
// Function to convert
// Binary to HexaDecimal
function bToHexaDecimal(s) {
let len = s.length, check = 0;
let num = 0, sum = 0, mul = 1;
let ans = new Array();
// Iterating through
// the bits backwards
for (let i = len - 1; i >= 0; i--) {
sum += (s[i].charCodeAt(0) - '0'.charCodeAt(0)) * mul;
mul *= 2;
check++;
// Computing the HexaDecimal
// Number formed so far
// and storing it in a vector.
if (check == 4 || i == 0) {
if (sum <= 9)
ans.push(String.fromCharCode(sum + '0'.charCodeAt(0)));
else
ans.push(String.fromCharCode(sum + 55));
// Reinitializing all
// variables for next group.
check = 0;
sum = 0;
mul = 1;
}
}
len = ans.length;
// Printing the Hexadecimal
// number formed so far.
for (let i = len - 1; i >= 0; i--)
document.write(ans[i]);
}
// Driver Code
let s = "100000101111";
// Function Call
bToHexaDecimal(s);
// This code is contributed by _saurabh_jaiswal
</script>
Output
82F
Approach#2: Using dictionary
Create a dictionary mapping each 4-bit binary number to its corresponding hexadecimal equivalent. Pad the input binary number with zeros at the beginning to make its length a multiple of 4. Split the padded binary number into 4-bit chunks and map each chunk to its corresponding hexadecimal equivalent.the hexadecimal equivalents to get the final hexadecimal number.
Algorithm
1. Create a dictionary hex_dict with keys as 4-bit binary numbers and values as their corresponding hexadecimal equivalents.
2. Pad the input binary number with zeros at the beginning to make its length a multiple of 4.
3. Initialize an empty string hex_num.
4. Loop through the binary number in steps of 4 bits.
5. For each 4-bit chunk, map it to its corresponding hexadecimal equivalent using the hex_dict and append the result to hex_num.
6. Return the final hexadecimal number.
#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
std::string binaryNum = "10101101";
// Create an unordered map to store
// binary-to-hexadecimal mappings
std::unordered_map<std::string, char> hexDict;
hexDict["0000"] = '0';
hexDict["0001"] = '1';
hexDict["0010"] = '2';
hexDict["0011"] = '3';
hexDict["0100"] = '4';
hexDict["0101"] = '5';
hexDict["0110"] = '6';
hexDict["0111"] = '7';
hexDict["1000"] = '8';
hexDict["1001"] = '9';
hexDict["1010"] = 'A';
hexDict["1011"] = 'B';
hexDict["1100"] = 'C';
hexDict["1101"] = 'D';
hexDict["1110"] = 'E';
hexDict["1111"] = 'F';
std::string hexNum = "";
int n = binaryNum.length();
// Pad the binary number with zeros at the beginning to
// make its length a multiple of 4
if (n % 4 != 0) {
binaryNum = std::string(4 - n % 4, '0') + binaryNum;
n = binaryNum.length();
}
// Convert the binary number to hexadecimal
for (int i = 0; i < n; i += 4) {
std::string hexChunk = binaryNum.substr(i, 4);
hexNum += hexDict[hexChunk];
}
std::cout << hexNum << std::endl;
return 0;
}
import java.util.HashMap;
public class BinaryToHexadecimal {
public static void main(String[] args) {
String binaryNum = "10101101";
HashMap<String, String> hexDict = new HashMap<>();
hexDict.put("0000", "0");
hexDict.put("0001", "1");
hexDict.put("0010", "2");
hexDict.put("0011", "3");
hexDict.put("0100", "4");
hexDict.put("0101", "5");
hexDict.put("0110", "6");
hexDict.put("0111", "7");
hexDict.put("1000", "8");
hexDict.put("1001", "9");
hexDict.put("1010", "A");
hexDict.put("1011", "B");
hexDict.put("1100", "C");
hexDict.put("1101", "D");
hexDict.put("1110", "E");
hexDict.put("1111", "F");
StringBuilder hexNum = new StringBuilder();
int n = binaryNum.length();
// Pad the binary number with zeros at the beginning to make its length a multiple of 4
if (n % 4 != 0) {
binaryNum = "0".repeat(4 - n % 4) + binaryNum;
n = binaryNum.length();
}
// Convert the binary number to hexadecimal
for (int i = 0; i < n; i += 4) {
String hexChunk = binaryNum.substring(i, i + 4);
hexNum.append(hexDict.get(hexChunk));
}
System.out.println(hexNum.toString());
}
}
binary_num = "10101101"
hex_dict = {
"0000": "0",
"0001": "1",
"0010": "2",
"0011": "3",
"0100": "4",
"0101": "5",
"0110": "6",
"0111": "7",
"1000": "8",
"1001": "9",
"1010": "A",
"1011": "B",
"1100": "C",
"1101": "D",
"1110": "E",
"1111": "F"
}
hex_num = ""
n = len(binary_num)
# Pad the binary number with zeros at the beginning to
# make its length a multiple of 4
if n % 4 != 0:
binary_num = "0" * (4 - n % 4) + binary_num
n = len(binary_num)
# Convert the binary number to hexadecimal
for i in range(0, n, 4):
hex_chunk = binary_num[i:i+4]
hex_num += hex_dict[hex_chunk]
print(hex_num)
using System;
using System.Collections.Generic;
public class GFG
{
public static void Main(string[] args)
{
string binaryNum = "10101101";
Dictionary<string, string> hexDict = new Dictionary<string, string>
{
{"0000", "0"},
{"0001", "1"},
{"0010", "2"},
{"0011", "3"},
{"0100", "4"},
{"0101", "5"},
{"0110", "6"},
{"0111", "7"},
{"1000", "8"},
{"1001", "9"},
{"1010", "A"},
{"1011", "B"},
{"1100", "C"},
{"1101", "D"},
{"1110", "E"},
{"1111", "F"}
};
string hexNum = "";
int n = binaryNum.Length;
// Pad the binary number with zeros at the beginning to make its length a multiple of 4
if (n % 4 != 0)
{
binaryNum = new string('0', 4 - n % 4) + binaryNum;
n = binaryNum.Length;
}
// Convert the binary number to hexadecimal
for (int i = 0; i < n; i += 4)
{
string hexChunk = binaryNum.Substring(i, 4);
hexNum += hexDict[hexChunk];
}
Console.WriteLine(hexNum);
}
}
// Function to convert a binary number to hexadecimal
function binaryToHexadecimal(binaryNum) {
const hexDict = new Map([
["0000", "0"],
["0001", "1"],
["0010", "2"],
["0011", "3"],
["0100", "4"],
["0101", "5"],
["0110", "6"],
["0111", "7"],
["1000", "8"],
["1001", "9"],
["1010", "A"],
["1011", "B"],
["1100", "C"],
["1101", "D"],
["1110", "E"],
["1111", "F"]
]);
let hexNum = "";
let n = binaryNum.length;
// Pad the binary number with zeros at the beginning to make its length a multiple of 4
if (n % 4 !== 0) {
binaryNum = "0".repeat(4 - n % 4) + binaryNum;
n = binaryNum.length;
}
// Convert the binary number to hexadecimal
for (let i = 0; i < n; i += 4) {
const hexChunk = binaryNum.substring(i, i + 4);
hexNum += hexDict.get(hexChunk);
}
return hexNum;
}
const binaryNum = "10101101";
const hexadecimalNum = binaryToHexadecimal(binaryNum);
console.log(hexadecimalNum);
Output
AD
Time complexity: O(n), where n is the length of the input binary number. The for loop runs n/4 times, each time accessing a dictionary value in constant time.
Space complexity: O(1). The space used is constant, as only a dictionary and a string are used to store the input and output values.