Program to convert a binary number to a decimal number in C.

Table of contents

No heading

No headings in the article.

include<stdio.h>
int main( ) 
{ int n,nsave,rem,d,j=l,dec=O;
  printf("Enter the number in binary :"); 
  scanf ("%d", &n) ;
  nsave=n; 
while (n>O)
 { 
    rem=n%lO; /*Itaking last digit1 */
    d=rem*j; 
    dec+=d; 
    j*=2; 
    n/=lO; /*skipping last digit*/ 
 } 
printf("Binary number = %d, Decimal number = %d\n",nsave,dec); }
OUTPUT :
     Enter the number in binary : 1101
     Binary number = 1101, Decimal number = 13

To convert a binary number to decimal, we extract binary digits from the right and add them after multiplying by powers of 2. This is somewhat similar to the program P5.9, only we have to multiply the digits by powers of 2 before adding them. This is how the loop works for binary number 1101. ----< Before loop starts: rem=garbage, d= garbage, dec=O, j=l, n=nsave=llOI After 1st iteration: rem=1, d=11, dec=1, j=2, n=110 After 2nd iteration: rem=O, d=02, dec=1 +0, j=4, n=ll After 3rd iteration: rem= I, d=1*4, dec=1+0+4, j=8, n=I After 4th iteration: rem=l, d=1 *8, dec=1+0+4+8, j=16, n=O Now the value of n becomes zero so the loop terminates. We have taken a variable nsave to save the value of the binary number, because the value of n gets changed after the loop execution. (The above program will be valid for binary numbers upto 11111 only, for larger numbers take long int).