Convert a binary number to hexadecimal number

08 Jun, 2022
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
 
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.
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++
Java
Python3
C#
Javascript
// 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 hexadecimalvoid 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 binarystring 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 aboveint main(){    string bin = "1111001010010100001.010110110011011";    cout << "Hexadecimal number = "         << convertBinToHex(bin);    return 0;    }
// Java implementation to convert a// binary number to hexadecimal numberimport java.io.*;import java.util.*; class GFG{ // Function to create map between binary// number and its equivalent hexadecimalstatic 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 binarystatic 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 codepublic static void main(String[] args){    String bin = "1111001010010100001.010110110011011";         System.out.print("Hexadecimal number = " +                      convertBinToHex(bin));}} // This code is contributed by jithin
## Python implementation to## convert a binary number to hexadecimal numberh ## Function to create map between binary## number and its equivalent hexadecimaldef 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 binarydef 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 codeif __name__=='__main__':     bin = "1111001010010100001.010110110011011"    print("Hexadecimal number =", convertBinToHex(bin));     # This code is contributed by subhamgoyal2014.
// 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 implementation to// convert a binary number to hexadecimal number // Function to create map between binary// number and its equivalent hexadecimalfunction 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 binaryfunction 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 abovelet 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.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
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
RishabhPrabhu
swetha_vazhakkat
jithin
surinderdawra388
phasing17
gautamgoel962
subhamgoyal2014
base-conversion
binary-representation
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7
Operators in C / C++
Prime Numbers
Program to find GCD or HCF of two numbers
Minimum number of jumps to reach end