This blog is under construction

Thursday 4 July 2013

C Program to convert octal to binary

How to convert octal value to binary equivalent?
Octal Value 747
(747) = (111)(100)(111) => 111100111
Find the binary value for each digit and append the outputs.

Write a C program to convert octal value to binary.


  #include <stdio.h>
  #include <string.h>
  #define MAXBINARYDIG 3

  char result[256];

  /* finds binary equivalent for given decimal value and update o/p */
  void decimalToBinary(int data) {
        int res = 0, i = 0, j = 0, mod, count = MAXBINARYDIG - 1;
        char val[MAXBINARYDIG + 1];

        /*
         * In our case, max length of binary equivalent of
         * given decimal value is 3.  So, we are storing '0'
         * at each index of val during intialization.
         * val[] = {'0', '0', '0'}
         */
        memset(val, '0', MAXBINARYDIG);
        /* convert decimal to binary format */
        while (data > 0) {
                mod = data % 2;
                val[count--] = mod + '0';
                data = data / 2;
        }
        /* terminate the string with null character */
        val[MAXBINARYDIG] = '\0';

        /* update the result */
        strcat(result, val);
  }

  int main() {
        char input[10], ch;
        int value = 0, power = 0, i = 0, j = 0, res;

        /* get the octal value from the user */
        printf("Enter your octal value:");
        fgets(input, 10, stdin);
        input[strlen(input) - 1] = '\0';

        memset(result, 0, 256);
        /* convert octal value to decimal */
        for (i = 0; i < strlen(input); i++) {
                ch = input[i];
                if (ch >='0'&& ch <= '7') {
                        /*
                         * input character is any value from 0 to 9
                         */
                        decimalToBinary(ch-'0');
                } else {
                        /*
                         * valid octal values 0-7, if the input
                         * doesn't belong to any of the above
                         * values, then its a wrong input
                         */
                        printf("Wrong Input!!!\n");
                        return (-1);
                }
        }
        printf("Equivalent Decimal Value: %s\n", result);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your octal value:747
  Equivalent Decimal Value: 111100111



No comments:

Post a Comment