Sunday, 15 March 2015

To convert a binary number to a decimal number Using C

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

void main()
{
int i = 0, j = 0, sum = 0 ;
long int n ;
clrscr() ;
printf("Enter the binary number : ") ;
scanf("%ld", &n) ;
if(n != 0)
{
i = n % 10 ;
if(i == 0 || i == 1)
{
while(n != 0)
{
i = n % 10 ;
sum = sum + i * pow(2, j) ;
n = n / 10 ;
j ++ ;
}
}
}
if(sum == 0)
printf("\nThe number is not a binary number") ;
else
printf("\nThe equivalent decimal number is : %d", sum) ;
getch() ;
}

RUN 1 :
~~~~~~~
Enter the binary number : 1100
The equivalent decimal number is : 12
RUN 2 :
~~~~~~~
Enter the binary number : 15
The number is not a binary number

No comments:

Post a Comment