C Program To Convert Binary To Decimal Number

How To Write a C Program To Convert Binary To Decimal Number in C Programming Language ?


Solution For C Program To Convert Binary To Decimal Number:
#include<stdio.h>
#include<conio.h>
#include<math.h>

void bin_dec(long int num)   // Function Definition
{
long int rem,sum=0,power=0;
while(num>0)
 {
 rem = num%10;
 num = num/10;
 sum = sum + rem * pow(2,power);
 power++;
 }

printf("Decimal number : %d",sum);
}
//-------------------------------------
void main()
{
long int num;
clrscr();

printf("Enter the Binary number (0 and 1): ");
scanf("%ld",&num);

bin_dec(num);

getch();
}
Output :
Enter the Binary number : 111
Decimal number : 7

Logic of This Program :

In the main function we have accepted the proper binary input i.e suppose we have accepted 111 as binary input.
printf("Enter the Binary number (0 and 1): ");
scanf("%ld",&num);
Inside the function while loop gets executed. Sample Dry run for the while loop is shown below -
Iterationnumremsumpower
Before Entering into Loop111Garbage00
After Iteration 111111
After Iteration 21132
After Iteration 30173

Algorithm for Binary to Decimal :

  1. Accept Number from User
  2. Divide Number by 10 and Store Remainder in variable rem
  3. Divide Original Number by 10.
sum = sum + rem * pow(2,power);
Inside the First Iteration power = 0. Power is Incremented in each Iteration.
  1. Calculate sum using the above formula, calculated sum is nothing but the decimal representation of the given binary number.
Tags:C Program To Convert Binary To Decimal Number, write a c program to convert binary to decimal number, decimal to binary conversion in c with explanation, c program to convert binary to decimal using for loop, c program to convert binary to decimal using recursion, c program to convert binary to decimal using while loop, c program to convert binary to decimal octal hexadecimal, c program to convert binary to decimal using function, c program to convert binary to decimal using bitwise operators.


Learn More :