C++ program to Convert Binary to Hexadecimal

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 NumberBinary NumbersHexadecimal Number
000000
100011
200102
300113
401004
501015
601106
701117
810008
910019
101010A
111011B
121100C
131101D
141110E
151111F

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