Monday, August 4, 2014

C Program to Convert the given Binary Number into Decimal

This C Program converts the given binary number into decimal. The program reads the binary number, does a modulo operation to get the remainder, multiples the total by base 2 and adds the modulo and repeats the steps.
Here is source code of the C program to covert binary number to decimal. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
  1. /*
  2.  * C program to convert the given binary number into decimal
  3.  */
  4. #include <stdio.h>
  5.  
  6. void main()
  7. {
  8.     int  num, binary_val, decimal_val = 0, base = 1, rem;
  9.  
  10.     printf("Enter a binary number(1s and 0s) \n");
  11.     scanf("%d", &num); /* maximum five digits */
  12.     binary_val = num;
  13.     while (num > 0)
  14.     {
  15.         rem = num % 10;
  16.         decimal_val = decimal_val + rem * base;
  17.         num = num / 10 ;
  18.         base = base * 2;
  19.     }
  20.     printf("The Binary number is = %d \n", binary_val);
  21.     printf("Its decimal equivalent is = %d \n", decimal_val);
  22. }

$ cc pgm38.c
$ a.out
Enter a binary number(1s and 0s)
10101001
The Binary number is = 10101001
Its decimal equivalent is = 169S

No comments:

Post a Comment