Wednesday, March 14, 2012

Printing the Decimal Equivalent of a Binary Number

Just as in the decimal number system, in which the rightmost digit has a positional value of 1, and the next digit left has a positional value of 10, then 100, then 1000, and so on, in the binary number system the rightmost digit has a positional value of 1, the next digit left has a positional value of 2, then 4, then 8, and so on.

e.g 1101 is 1 * 1 + 0 * 2 + 1 *  4 + 1 * 8 or 1 + 0 + 4 + 8 or 13


/*
   title: printingDecimalEquivalentOfABinaryNumber
   author: aeriqusyairi
   date: dec27 2011
*/
#include<stdio.h>
#include<stdlib.h>

int main(){
   int binary=0,decimal=0,counter=0,two=1,digit=0;
   printf("Input a binary number: ");
   scanf("%d", &binary);    
   do{
      counter = binary;
      digit = binary % 10;
      decimal += digit * two; 
      binary /= 10;
      if(two == 1)
         two++;
      else
         two *= 2;
   }while(counter >=1);
   printf("%d\n", decimal);
   system("pause");
   return 0;
}

No comments:

Post a Comment