C++ Program to Convert Binary to Hexadecimal

Write C++ Program to Convert Binary to Hexadecimal

// CPP Program to Convert Binary to Hexadecimal

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

using namespace std;

Binary_to_decimal(int n)
{
	int ans = 0, i = 0;
	while(n != 0)
	{
		int digit = n % 10;  //here we take the last digit
		if(digit == 1)
		{
			ans = (digit * pow(2,i)) + ans;	  //formula for the conversion
		}
		n = n / 10;				// reducing the number
		i++;
	}
	return ans;
}

int main()		//here first we convert Binary to Decimal and then decimal to octal
{
	int n;

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


	int bcd= Binary_to_decimal(n);
	cout << "\nThe Decimal Number is :--> " << bcd;

	int i = 0,ans2 = 0;
	while(bcd != 0)
	{
		int digit = bcd%16;
		bcd = bcd/16;
		ans2 = (digit * pow(10, i)) + ans2;
		i++;
	}

	cout << "\nThe Hexadecimal Number is :--> " << ans2;

	return 0;
}

Output:

Enter the Binary Number :--> 110101

The Decimal Number is :--> 53
The Hexadecimal Number is :--> 35

≪ Previous | Next ≫