C++ Program to Convert Hexadecimal to Binary

C++ Program to Convert Hexadecimal to Binary

Write C++ Program to Convert Hexadecimal to Binary

// Write CPP Program to Convert Hexadecimal to Binary

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
	int n, ans = 0, B[100];

	cout << "Enter the Hexadecimal Number :--> ";
	cin >> n;

	int i = 0;

	while(n != 0)
	{
		int digit = n % 10;
		ans = ans + (digit * pow(16, i));
		n = n / 10;
		i++;
	}
	cout << "\nThe Decimal Number is :--> " << ans;

	int j = 0, k;
	while(ans > 0)
	{
		B[j] = ans % 2;			//to store the remainder in array
		ans = ans >> 1;
		j++;
	}
	cout << "\nThe Binary Number is :--> ";
	for(k = j - 1; k >= 0; k--)
	{
		cout << B[k];
	}
	return 0;
}

Output:

Enter the Hexadecimal Number :--> 221

The Decimal Number is :--> 545
The Binary Number is :--> 1000100001