C Programming
Computer Programming

C Program using function to Convert Binary number to Octal



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

\* C Program using function to Convert Binary number to Octal *\

# include < stdio.h >
# include < conio.h >
int   convertBinarytoOctal( long long binaryNumber ) ;
int   main( )
{

long long binaryNumber, k ;
int count = 0 ;
printf( "\n Enter a binary number: " ) ;
scanf( "%lld", &binaryNumber ) ;
k = binaryNumber ;
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 !", binaryNumber ) ;
else
      printf(" The Octal Number of Entered Binary Number %lld is = %d ", binaryNumber, convertBinarytoOctal(binaryNumber) ) ;
return 0 ;

}

int   convertBinarytoOctal( long long binaryNumber ) ;
{

int octalNumber = 0, decimalNumber = 0, i = 0 ;
while( binaryNumber != 0 )
{
      decimalNumber += (binaryNumber%10) * pow( 2, i ) ;
      ++i ;
      binaryNumber/=10 ;
}
i = 1 ;

while ( decimalNumber != 0 )
{
      octalNumber += (decimalNumber % 8) * i ;
      decimalNumber /= 8 ;
      i *= 10 ;
}
return octalNumber ;

}

Output of Program :

Output of C Program using function to Convert Binary number to Octal