Thursday, 21 August 2014

Filled Under: ,

C program to convert binary number to decimal

Share
Here is a simple C program to convert binary number to decimal is given,which takes binary  number(1s & 0s) as input.and after execution it will give decimal number equivalent to given binary number.For example if you insert 111 as input then it print 7 as output on output screen. This C Program converts the given binary number into decimal. The program reads the binary number, does a modulo operation to get theremainder, multiples the total by base 2 and adds the modulo and repeats the steps.

C Program to convert binary number to decimal

#include <stdio.h>
void main()
{
   int  num, binary_val, decimal_val = 0, base = 1, rem;
   printf("Enter a binary number(1s and 0s) n");
   scanf("%d", &num); /* maximum five digits */
   binary_val = num;
     while (num > 0)
      {
         rem = num % 10;
         decimal_val = decimal_val + rem * base;
         num = num / 10 ;
         base = base * 2;
      }
    printf("The Binary number is = %d n", binary_val);
    printf("Its decimal equivalent is = %d n", decimal_val);
 }




Output:
Enter a binary number(1s and 0s)
10101011
The Binary number is = 10101011
Its decimal equivalent is = 171