Convert a binary number to hexadecimal number

The problem is to convert the given binary number to its equivalent hexadecimal number.
The input could be very large and may not fit even into unsigned long long int.

Examples:

Input : 110001110
Output : 18E

Input : 1111001010010100001.010110110011011
Output : 794A1.5B36



Memorize the value of a 4-digit binary number in hexadecimal from this if we don’t know the relation.

A simple approach is to first convert the binary number to decimal number and then convert decimal to hexadecimal.

An efficient approach for large numbers is to consider the binary input as a string of characters and then follow the steps:

  1. Get length of substring to the left and right of the decimal point(‘.’) as left_len and right_len.
  2. If left_len is not a multiple of 4 add min number of 0’s in the beginning to make length of left substring a multiple of 4.
  3. If right_len is not a multiple of 4 add min number of 0’s in the end to make length of right substring a multiple of 4.
  4. Now, from the left extract one by one substrings of length 4 and add its corresponding hex code to the result.
  5. If in between a decimal(‘.’) is ecountered then add it to the result.
// 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;     

Output:

Hexadecimal number = 794A1.5B36

Time Complexity: O(n), where n is the length of string.

This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.



My Personal Notes arrow_drop_up