Program to convert a binary number to hexadecimal number
Last Updated :
02 Aug, 2024
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: 110001110
Output: 18E
Input: 1111001010010100001.010110110011011
Output: 794A1.5B36 794A1D9B
Approach 1:
Binary Number: A binary number is a number expressed in the base-2 binary numeral system, which uses only two symbols: which are 0 (zero) and 1 (one).
4HexaDecimal Number: A hexadecimal number is a positional numeral system with a radix, or base, of 16 and uses sixteen distinct symbols: which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F.

Convert Binary to HexaDecimal:
We all know that, 24 = 16 1.
In other words, single digit in base 16 can be represented using 4 digits in base 2.

To convert Binary number to HexaDecimal, the below steps are taken:
- Group the given Binary Number into groups of 4 bits, each group taken individually from the left and right of the decimal point.
- Get length of substring to the left and right of the decimal point('.') as left_len and right_len.
- If left_len is not a multiple of 4, i.e., grouping into exact group of 4 bits is not possible, then add minimum number of 0's in the beginning to make length of left substring a multiple of 4.
- Similarly, If right_len is not a multiple of 4, then add minimum number of 0's in the end to make length of right substring a multiple of 4.
- Now, from the left, extract each group (substrings of length 4) one by one and add its corresponding Hexadecimal code to the result.
- If in between a decimal('.') is encountered then add it to the result.
Below is the implementation of the above approach:
C++
// C++ implementation to
// convert a binary number to hexadecimal number
#include <bits/stdc++.h>
using namespace std;
// Function to create map between binary
// number and its equivalent hexadecimal
void createMap(unordered_map<string, char> *um)
{
(*um)["0000"] = '0';
(*um)["0001"] = '1';
(*um)["0010"] = '2';
(*um)["0011"] = '3';
(*um)["0100"] = '4';
(*um)["0101"] = '5';
(*um)["0110"] = '6';
(*um)["0111"] = '7';
(*um)["1000"] = '8';
(*um)["1001"] = '9';
(*um)["1010"] = 'A';
(*um)["1011"] = 'B';
(*um)["1100"] = 'C';
(*um)["1101"] = 'D';
(*um)["1110"] = 'E';
(*um)["1111"] = 'F';
}
// function to find hexadecimal
// equivalent of binary
string convertBinToHex(string bin)
{
int l = bin.size();
int t = bin.find_first_of('.');
// length of string before '.'
int len_left = t != -1 ? t : l;
// add min 0's in the beginning to make
// left substring length divisible by 4
for (int i = 1; i <= (4 - len_left % 4) % 4; i++)
bin = '0' + bin;
// if decimal point exists
if (t != -1)
{
// length of string after '.'
int len_right = l - len_left - 1;
// add min 0's in the end to make right
// substring length divisible by 4
for (int i = 1; i <= (4 - len_right % 4) % 4; i++)
bin = bin + '0';
}
// create map between binary and its
// equivalent hex code
unordered_map<string, char> bin_hex_map;
createMap(&bin_hex_map);
int i = 0;
string hex = "";
while (1)
{
// one by one extract from left, substring
// of size 4 and add its hex code
hex += bin_hex_map[bin.substr(i, 4)];
i += 4;
if (i == bin.size())
break;
// if '.' is encountered add it
// to result
if (bin.at(i) == '.')
{
hex += '.';
i++;
}
}
// required hexadecimal number
return hex;
}
// Driver program to test above
int main()
{
string bin = "1111001010010100001.010110110011011";
cout << "Hexadecimal number = "
<< convertBinToHex(bin);
return 0;
}
Java
// Java implementation to convert a
// binary number to hexadecimal number
import java.io.*;
import java.util.*;
class GFG{
// Function to create map between binary
// number and its equivalent hexadecimal
static void createMap(Map<String, Character> um)
{
um.put("0000", '0');
um.put("0001", '1');
um.put("0010", '2');
um.put("0011", '3');
um.put("0100", '4');
um.put("0101", '5');
um.put("0110", '6');
um.put("0111", '7');
um.put("1000", '8');
um.put("1001", '9');
um.put("1010", 'A');
um.put("1011", 'B');
um.put("1100", 'C');
um.put("1101", 'D');
um.put("1110", 'E');
um.put("1111", 'F');
}
// Function to find hexadecimal
// equivalent of binary
static String convertBinToHex(String bin)
{
int l = bin.length();
int t = bin.indexOf('.');
// Length of string before '.'
int len_left = t != -1 ? t : l;
// Add min 0's in the beginning to make
// left substring length divisible by 4
for(int i = 1;
i <= (4 - len_left % 4) % 4;
i++)
bin = '0' + bin;
// If decimal point exists
if (t != -1)
{
// Length of string after '.'
int len_right = l - len_left - 1;
// Add min 0's in the end to make right
// substring length divisible by 4
for(int i = 1;
i <= (4 - len_right % 4) % 4;
i++)
bin = bin + '0';
}
// Create map between binary and its
// equivalent hex code
Map<String,
Character> bin_hex_map = new HashMap<String,
Character>();
createMap(bin_hex_map);
int i = 0;
String hex = "";
while (true)
{
// One by one extract from left, substring
// of size 4 and add its hex code
hex += bin_hex_map.get(
bin.substring(i, i + 4));
i += 4;
if (i == bin.length())
break;
// If '.' is encountered add it
// to result
if (bin.charAt(i) == '.')
{
hex += '.';
i++;
}
}
// Required hexadecimal number
return hex;
}
// Driver code
public static void main(String[] args)
{
String bin = "1111001010010100001.010110110011011";
System.out.print("Hexadecimal number = " +
convertBinToHex(bin));
}
}
// This code is contributed by jithin
Python
## Python implementation to
## convert a binary number to hexadecimal numberh
## Function to create map between binary
## number and its equivalent hexadecimal
def createMap(um):
um["0000"] = '0'
um["0001"] = '1'
um["0010"] = '2'
um["0011"] = '3'
um["0100"] = '4'
um["0101"] = '5'
um["0110"] = '6'
um["0111"] = '7'
um["1000"] = '8'
um["1001"] = '9'
um["1010"] = 'A'
um["1011"] = 'B'
um["1100"] = 'C'
um["1101"] = 'D'
um["1110"] = 'E'
um["1111"] = 'F'
## function to find hexadecimal
## equivalent of binary
def convertBinToHex(bin):
l = len(bin)
t = bin.find('.')
## length of string before '.'
len_left = None
if (t != -1):
len_left = t
else:
len_left = l
## add min 0's in the beginning to make
## left substring length divisible by 4
for i in range(1, 1 + (4 - len_left % 4) % 4):
bin = '0' + bin;
## if decimal point exists
if (t != -1):
## length of string after '.'
len_right = l - len_left - 1
## add min 0's in the end to make right
## substring length divisible by 4
for i in range(1, 1 + (4 - len_right % 4) % 4):
bin = bin + '0'
## create map between binary and its
## equivalent hex code
bin_hex_map = {}
createMap(bin_hex_map)
i = 0;
hex = ""
while True:
## one by one extract from left, substring
## of size 4 and add its hex code
hex += bin_hex_map[bin[i: i+4]];
i += 4;
if (i == len(bin)):
break;
## if '.' is encountered add it
## to result
if (bin[i] == '.'):
hex += '.';
i+=1
## required hexadecimal number
return hex;
## Driver code
if __name__=='__main__':
bin = "1111001010010100001.010110110011011"
print("Hexadecimal number =", convertBinToHex(bin));
# This code is contributed by subhamgoyal2014.
C#
// C# implementation to convert a
// binary number to hexadecimal number
using System;
using System.Collections.Generic;
public class GFG {
// Function to create map between binary
// number and its equivalent hexadecimal
static IDictionary<string, char>
createMap(IDictionary<string, char> um)
{
um.Add("0000", '0');
um.Add("0001", '1');
um.Add("0010", '2');
um.Add("0011", '3');
um.Add("0100", '4');
um.Add("0101", '5');
um.Add("0110", '6');
um.Add("0111", '7');
um.Add("1000", '8');
um.Add("1001", '9');
um.Add("1010", 'A');
um.Add("1011", 'B');
um.Add("1100", 'C');
um.Add("1101", 'D');
um.Add("1110", 'E');
um.Add("1111", 'F');
return um;
}
// Function to find hexadecimal
// equivalent of binary
static String convertBinToHex(String bin)
{
int i;
int l = bin.Length;
int t = bin.IndexOf('.');
// Length of string before '.'
int len_left = t != -1 ? t : l;
// Add min 0's in the beginning to make
// left substring length divisible by 4
for (i = 1; i <= (4 - len_left % 4) % 4; i++)
bin = '0' + bin;
// If decimal point exists
if (t != -1) {
// Length of string after '.'
int len_right = l - len_left - 1;
// Add min 0's in the end to make right
// substring length divisible by 4
for (i = 1; i <= (4 - len_right % 4) % 4; i++)
bin = bin + '0';
}
// Create map between binary and its
// equivalent hex code
IDictionary<string, char> bin_hex_map
= new Dictionary<string, char>();
bin_hex_map = createMap(bin_hex_map);
i = 0;
string hex = "";
while (true) {
// One by one extract from left, substring
// of size 4 and add its hex code
hex += bin_hex_map[bin.Substring(i, 4)];
i += 4;
if (i == bin.Length)
break;
// If '.' is encountered add it
// to result
if (bin[i] == '.') {
hex += '.';
i++;
}
}
// Required hexadecimal number
return hex;
}
public static void Main(string[] args)
{
string bin = "1111001010010100001.010110110011011";
Console.WriteLine("Hexadecimal number = "
+ convertBinToHex(bin));
}
}
// This code is contributed by phasing17.
JavaScript
// JavaScript implementation to
// convert a binary number to hexadecimal number
// Function to create map between binary
// number and its equivalent hexadecimal
function createMap(um)
{
um.set("0000", '0');
um.set("0001", '1');
um.set("0010", '2');
um.set("0011", '3');
um.set("0100", '4');
um.set("0101", '5');
um.set("0110", '6');
um.set("0111", '7');
um.set("1000", '8');
um.set("1001", '9');
um.set("1010", 'A');
um.set("1011", 'B');
um.set("1100", 'C');
um.set("1101", 'D');
um.set("1110", 'E');
um.set("1111", 'F');
}
// function to find hexadecimal
// equivalent of binary
function convertBinToHex(bin)
{
let l = bin.length;
let t = bin.indexOf('.');
// length of string before '.'
let len_left = t != -1 ? t : l;
// add min 0's in the beginning to make
// left substring length divisible by 4
for (let i = 1; i <= (4 - len_left % 4) % 4; i++)
bin.unshift('0');
// if decimal point exists
if (t != -1)
{
// length of string after '.'
let len_right = l - len_left - 1;
// add min 0's in the end to make right
// substring length divisible by 4
for (let i = 1; i <= (4 - len_right % 4) % 4; i++)
bin.push('0');
}
// create map between binary and its
// equivalent hex code
let bin_hex_map = new Map();
createMap(bin_hex_map);
let i = 0;
let hex = new Array();
while (1)
{
// one by one extract from left, substring
// of size 4 and add its hex code
hex.push(bin_hex_map.get(bin.slice(i, i+4).join('')));
i = i + 4;
if (i == bin.length)
break;
// if '.' is encountered add it
// to result
if (bin[i] == '.')
{
hex.push('.');
i = i + 1;
}
}
// required hexadecimal number
return hex;
}
// Driver program to test above
let bin = "1111001010010100001.010110110011011";
console.log("Hexadecimal number =", convertBinToHex(bin.split('')).join(''));
// The code is contributed by Gautam goel (gautamgoel962)
Output:
Hexadecimal number = 794A1.5B36
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n) , space by map
Approach 2: Another approach to convert Binary Number to Hexadecimal number is to first convert the binary number to decimal number and then convert the obtained decimal number to equivalent hexadecimal number.
Practice Questions:
(1) Convert the binary number 111000 to hexa-decimal.
(2) Convert the binary number 100100001 to hexa-decimal.
(3) Convert the binary number 1001001111 to hexa-decimal.
(4) What is the binary equivalent of hexa-decimal number A7C5.
(5) What is the binary equivalent of hexa-decimal number 2A.FF.
Answers:
(1) 38
(2) 121
(3) 24F
(4) 1010011111000101
(5) 101010.11111111
Method 3: This method is only for the number which does not contain any decimal point( . )
1. The zfill() function is used to add leading zeros to the binary number so that it can be divided into groups of four bits each.
2. The hex_dict dictionary is used to map each group of four bits to its hexadecimal equivalent.
3. The loop iterates over the binary number in groups of four bits each, and converts each group to its hexadecimal equivalent using the hex_dict dictionary.
4. The hexadecimal equivalent of each group is appended to the hexadecimal variable.
C++14
#include <iostream>
#include <string>
#include <unordered_map>
std::string bin_to_hex(std::string binary) {
binary = std::string(binary.length() % 4 ? 4 - binary.length() % 4 : 0, '0') + binary;
std::unordered_map<std::string, char> 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'}
};
std::string hexadecimal;
for (size_t i = 0; i < binary.length(); i += 4) {
std::string group = binary.substr(i, 4);
hexadecimal += hex_dict[group];
}
return hexadecimal;
}
int main() {
std::string binary = "110001110";
std::cout << bin_to_hex(binary) << std::endl;
return 0;
}
Java
public class Main {
public static String binToHex(String binary) {
binary = String.format("%" + (int)Math.ceil(binary.length() / 4.0) * 4 + "s", binary).replace(' ', '0');
String hex = "";
String[] hexDict = {"0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "A", "B", "C", "D", "E", "F"};
for (int i = 0; i < binary.length(); i += 4) {
String group = binary.substring(i, i + 4);
hex += hexDict[Integer.parseInt(group, 2)];
}
return hex;
}
public static void main(String[] args) {
String binary = "110001110";
String hex = binToHex(binary);
System.out.println(hex);
}
}
Python
def bin_to_hex(binary):
binary = binary.zfill((len(binary) // 4 + 1) * 4)
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'}
hexadecimal = ''
for i in range(0, len(binary), 4):
group = binary[i:i + 4]
hexadecimal += hex_dict[group]
return hexadecimal
binary = "110001110"
print(bin_to_hex(binary))
C#
using System;
class Program {
static string bin_to_hex(string binary) {
binary = binary.PadLeft((binary.Length / 4 + 1) * 4, '0');
string[] hex_dict = {"0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "A", "B", "C", "D", "E", "F"};
string hexadecimal = "";
for (int i = 0; i < binary.Length; i += 4) {
string group = binary.Substring(i, 4);
int index = Convert.ToInt32(group, 2);
hexadecimal += hex_dict[index];
}
return hexadecimal;
}
static void Main(string[] args) {
string binary = "110001110";
string hexadecimal = bin_to_hex(binary);
Console.WriteLine(hexadecimal);
}
}
JavaScript
function binToHex(binary) {
binary = "0".repeat(binary.length % 4 ? 4 - binary.length % 4 : 0) + binary;
const hexDict = {
"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 hexadecimal = "";
for (let i = 0; i < binary.length; i += 4) {
const group = binary.substr(i, 4);
hexadecimal += hexDict[group];
}
return hexadecimal;
}
const binary = "110001110";
console.log(binToHex(binary));
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem