This blog is under construction

Saturday 6 July 2013

C program to convert binary to decimal using functoins

Write a C program to convert binary to decimal using functions.


  #include <stdio.h>

  /* find 2^findPower value */
  int findPower(int input, int power) {
        int i = 0, result = 1;

        /* 2^0 is 1 */
        if (power == 0)
                return 1;

        /* find 2^findPower value */
        for (i = 0; i < power; i++) {
                result = result * input;
        }

        /* return the calculated value */
        return result;
  }

  /* converts binary value to decimal */
 int binaryToDecimal(int input) {
        int result = 0, rem, i = 0;
        while (input > 0) {
                rem = input % 10;
                result = result + (rem * findPower(2, i));
                input = input / 10;
                i++;
        }
        return (result);

  }

  int main() {
        int input, result = 0, rem;

        /* get the input from the user */
        printf("Enter your input:");
        scanf("%d", &input);

        /* binary to decimal */
        result = binaryToDecimal(input);

        /* print the resultant decimal value */
        printf("Result: %d\n", result);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input:1111
  Result: 15



No comments:

Post a Comment