This is a C++ Program to Convert a Binary Number to its Hexadecimal Equivalent. Before that, you must have knowledge of the following topics in C++.
Binary number
The binary numbers are based on 0 and 1, so it is a base 2 number. They are the combination of 0 and 1. For example, 1001, 110101, etc.
Hexadecimal number
The hexadecimal number is represented with a base of 16. It has digits from 0 to 15 to represent, However after 9 the values are represented in Alphabet till 15 such as 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E, and 15 as F.
Now let us go through a program for Binary to hexadecimal conversion in C++.
C++ Program to Convert Binary to Hexadecimal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #include <iostream> #include <math.h> using namespace std; int main() { int hexNumber[100]; int i = 1, j = 0, rem, dec = 0, binNumber; cout << "Enter a Binary number: "; cin >> binNumber; while (binNumber > 0) { rem = binNumber % 2; dec = dec + rem * i; i = i * 2; binNumber = binNumber / 10; } i = 0; while (dec != 0) { hexNumber[i] = dec % 16; dec = dec / 16; i++; } cout << "Equivalent Hexadecimal value: "; for (j = i - 1; j >= 0; j--) { if (hexNumber[j] > 9) { cout << (char)(hexNumber[j] + 55); } else { cout << hexNumber[j]; } } } |
Output:
Enter a Binary number: 11111
Equivalent Hexadecimal value: 1F
You may go through the vice-versa program: