In this article, we are going to learn how to convert a binary number to an equivalent Hexadecimal number. Here we are going to learn about two number systems one is binary and another is Hexadecimal.
Binary numbers are base 2 numbers and represented in 0s and 1s. Hexadecimal numbers are base 16 numbers and represented in numbers from 0 to 9 and A to F.
Decimal Number | Binary Numbers | Hexadecimal Number |
0 | 0000 | 0 |
1 | 0001 | 1 |
2 | 0010 | 2 |
3 | 0011 | 3 |
4 | 0100 | 4 |
5 | 0101 | 5 |
6 | 0110 | 6 |
7 | 0111 | 7 |
8 | 1000 | 8 |
9 | 1001 | 9 |
10 | 1010 | A |
11 | 1011 | B |
12 | 1100 | C |
13 | 1101 | D |
14 | 1110 | E |
15 | 1111 | F |
C++ program to convert binary to hexadecimal number
#include<iostream>
using namespace std;
int main()
{
long long binNum,tempBin;
int hex=0;
int mul=1,chk=1;
int remainder;
int iter=0;
char hexNum[20];
cout <<"Please enter 8 bit binary number : ";
cin >> binNum;
tempBin = binNum;
while(binNum != 0)
{
remainder = binNum%10;
hex = hex + (remainder*mul);
if(chk%4==0)
{
if(hex<10)
hexNum[iter] = hex+48;
else
hexNum[iter] = hex+55;
mul = 1;
hex = 0;
chk = 1;
iter++;
}
else
{
mul = mul*2;
chk++;
}
binNum = binNum/10;
}
if(chk!=1)
hexNum[iter] = hex+48;
if(chk==1)
iter--;
cout<< "\nHexaDecimal Equivalent to Binary number = " << tempBin << " is ";
for(int k=iter; k>=0; k--)
{
cout<<hexNum[k];
}
cout<<endl;
return 0;
}
Output
Please enter 8 bit binary number : 10101010
HexaDecimal Equivalent to Binary number = 10101010 is AA
Please enter 8 bit binary number : 1111
HexaDecimal Equivalent to Binary number = 1111 is F