C Programming
Computer Programming

C Program using function to Convert a binary number to decimal



Write a Program in C using function to Convert a binary number to decimal

\* C Program using function to Convert a binary number to decimal *\

# include < stdio.h >
# include < conio.h >
int   convertBinaryToDecimal( long long n ) ;
int   main( )
{

long long n, k ;
int count = 0 ;
printf("\n Enter a binary number: ") ;
scanf( "%lld", &n ) ;
k = n ;
while( k >0 )
{
      int rem = 0 ;
      rem = k % 10 ;
      k = k / 10 ;
      if( rem > 1 )
      {
            count = 1 ;
            break ;
      }
}

if( count == 1 )
      printf(" Entered number %d is not a binary number !", n ) ;
else
      printf(" Decimal of Binary : %lld is = %d ", n, convertBinaryToDecimal(n)) ;
return 0 ;

}

int   convertBinaryToDecimal( long long n ) ;
{

int decimalNumber = 0, i = 0, remainder ;
while ( n != 0 )
{
      remainder = n%10 ;
      n /= 10 ;
      decimalNumber += remainder * pow( 2, i ) ;
      ++i ;
}
return decimalNumber ;

}

Output of Program :

Output of C Program using function to Convert a binary number to decimal