About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Tuesday, September 3, 2013

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

Note : 

This program is for beginners (not for Experts) that’s why we haven’t provided any Validations while accepting the input. Please provide proper binary input to this program i.e (0 and 1).

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.

No comments: