How to convert a number from hexadecimal to binary in C++

In this shot, we will discuss how to convert a hexadecimal number to a binary number.

We will use a while loop and switch statement to do this conversion.

Let’s look at the image below to understand how this conversion works.

Hexadecimal to Binary Conversion

The hexadecimal has a base of 16 (0-15) and the binary number has a base of 2 (0 and 1). We will use a while loop; in the loop, we use the switch statement and will predefine the values for the given input.

Let’s look at the code below to understand this better.

#include <iostream>
using namespace std;
int main() {
int i=0;
char hex[10];
cin>>hex;
cout<<"The value in the binary form is = ";
while(hex[i])
{
switch(hex[i])
{
case '0':
cout<<"0000";
break;
case '1':
cout<<"0001";
break;
case '2':
cout<<"0010";
break;
case '3':
cout<<"0011";
break;
case '4':
cout<<"0100";
break;
case '5':
cout<<"0101";
break;
case '6':
cout<<"0110";
break;
case '7':
cout<<"0111";
break;
case '8':
cout<<"1000";
break;
case '9':
cout<<"1001";
break;
case 'A':
case 'a':
cout<<"1010";
break;
case 'B':
case 'b':
cout<<"1011";
break;
case 'C':
case 'c':
cout<<"1100";
break;
case 'D':
case 'd':
cout<<"1101";
break;
case 'E':
case 'e':
cout<<"1110";
break;
case 'F':
case 'f':
cout<<"1111";
break;
default:
cout<<"--Invalid Hex Digit ("<< hex[i] <<")--";
}
i++;
}
return 0;
}

Enter the input below

Explanation

Enter a number in the input section.

  • In lines 5 and 6, we initialize the i and hex variables.

  • In line 7, we take the input hex.

  • In line 8, we print the binary value of its hexadecimal equivalent.

  • From lines 9 to 71, we initialize a while loop. In the loop, we use a switch statement where we have given the cases to print those binary values for the given input.

In this way, we can convert a hexadecimal number to a binary number in C++.

Free Resources