Open In App
Related Articles
• Write an Interview Experience
• Mathematical Algorithms

# Convert a binary number to hexadecimal number

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.

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:

1. Group the given Binary Number into groups of 4 bits, each group taken individually from the left and right of the decimal point.
2. Get length of substring to the left and right of the decimal point(‘.’) as left_len and right_len.
3. 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.
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.
5. Now, from the left, extract each group (substrings of length 4) one by one and add its corresponding Hexadecimal code to the result.
6. 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 ``using` `namespace` `std;` `// Function to create map between binary``// number and its equivalent hexadecimal``void` `createMap(unordered_map *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 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 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 bin_hex_map = ``new` `HashMap();``    ``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`

## Python3

 `## 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 ``#include ``#include ` `std::string bin_to_hex(std::string binary) {``    ``binary = std::string(binary.length() % 4 ? 4 - binary.length() % 4 : 0, ``'0'``) + binary;``    ``std::unordered_map 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);``    ``}``}`

## Python3

 `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))`

## 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));`

## 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);``    ``}``}`

Output

`18E`

Time Complexity: O(n)
Auxiliary Space: O(1)

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.