A Dec-Bin Solution

#include <stdio.h>

#define FALSE 0
#define TRUE !0

int printInBase( int n, int base );
int bin2dec( long int bn );

int bderror;

int main()
{
  int choice;
  int dnum;
  long int bnum;

  printf( "Bin <-> Dec Converter by Thomas Colthurst\n" );
  do
    {
      printf( "\nOptions:\n" );
      printf( "  1)  Convert decimal number to binary\n" );
      printf( "  2)  Convert binary number to decimal\n" );
      printf( "  3)  Exit program\n" );
      printf( "\nChoice: " );
      scanf( "%d", &choice ); 

    switch( choice )
      {
      case 1:
        printf( "Enter positive decimal number: " );
        scanf( "%d", &dnum );
        printf( "Decimal %d is ", dnum );
        if ( printIn( dnum, 2 ) == 0 )
          {
          printf( " in binary.\n" );
          }
        else
          {
          printf( "not a valid input.\n" );
          }
        break;

      case 2:
        printf( "Enter binary number: " );
        scanf( "%ld", &bnum );
        dnum = bin2dec( bnum );
        if ( bderror )
          {
          printf( "Invalid input.\n" );
          }
        else
          {
          printf( "Binary %ld is %d in decimal.\n", bnum, dnum );
          }
        break;

      case 3:
        printf( "Bye bye.\n" );
        break;
   
      default:
        printf( "Unknown option.\n" );
        break;
      }

    }
  while( choice != 3 );

  return 0;
}



/* prints out positive n in base base */
/* prints out nothing for 0 and infinite loops for negative n */
/* designed to be called by printInBase */

void printNextBaseDigit( int n, int base )
{
   if ( n > 0 )
     {
     printNextBaseDigit( n / base, base );
     printf( "%d", n % base );
     }
}


/* prints out nonnegative n in base base */
/* prints out nothing and returns 1 for negative n */
/* returns 0 otherwise */

int printInBase( int n, int base )
{
  int tmp;
  
   if ( n == 0 )
     {
     printf( "0" );
     return 0; 
     }

   if ( n > 0 )
     {
     printNextBaseDigit( n, base );
     return 0;
     }
   else
     {
     return 1;
     }

}


/* returns bn, de-encoded from binary-decimal */
/* sets global variable bderror to TRUE and returns 0  */
/*      if any of bn's decimal digits are other than 0 or 1 */
/* otherwise sets bderror to FALSE and returns de-encoded bn */
 
int bin2dec( long int bn )
{
  int d;
  int power;
  int currentBit;

  bderror = FALSE;

  if ( bn < 0 )
    {
    return -bin2dec( -bn );
    }

  d = 0;
  power = 1;
  while ( ( bn > 0 ) && ( !bderror ) )
    {
    currentBit = bn % 10;
    if ( (currentBit < 2 ) && ( currentBit >= 0 ) )
      {
      d = d + currentBit * power;
      power = power * 2;
      bn = bn / 10;
      }
    else
      {
      bderror = TRUE;
      d = 0;
      } 
    }

  return d;
}


Next Slide