C Program to Convert Binary to Hexadecimal

C Program to Convert Binary to Hexadecimal

Write C Program to Convert Binary to Hexadecimal

// Write C Program to Convert Binary to Hexadecimal

#include <stdio.h>
#include <math.h>

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;

	printf("Enter the Binary Number :--> ");
	scanf("%d", &n);


	int bcd= Binary_to_decimal(n);
	printf("\nThe Decimal Number is :--> %d", bcd);

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

	printf("\nThe Hexadecimal Number is :--> %d ", ans2);

	return 0;
}

Output:

Enter the Binary Number :--> 110101

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