This blog is under construction

Friday 5 July 2013

C program to convert binary to octal

How to convert binary value to octal equivalent?
Binary value 111101100
111101100 => (111) (101) (100) => 754
  • Group the binary values(3 digits in each group).
  • Find the hexadecimal value for each group and append the outputs.

Write a C program to convert binary value to octal.


  #include <stdio.h>
  #include <string.h>
  #include <math.h>

  /* binary to octal conversion */
  void binaryToOctal(char *data) {
        int i = 0, res = 0, val = 0, count = 2;

        printf("Equivalent Octal Value: ");
        /*
         * find octal value for every 3 digit
         * (start from MSB) and print it
         */
        while (data[i] != '\0') {
                val = val + (data[i] - '0') * pow(2, count);
                i++;
                count--;
                if (i % 3 == 0) {
                        printf("%d", val);
                        val = 0, count = 2;
                }
        }
        printf("\n");
  }

  int main() {
        char input[100], temp[512], ch;
        int value = 0, power = 0, i = 0, j = 0, res, len;

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

        len = strlen(input);
        /* 
         * doing 3 digit alignment for the above obtained binary
         * input.  For example, if the binary input is 1, make
         * it three digit aligned.  001
         */
        if (len % 3 != 0) {
                for (i = len; i >= 0; i--) {
                        input[i + (3 - (len % 3))] = input[i];
                }
                len = 3 - (len % 3);
                while (len > 0) {
                        input[len - 1] = '0';
                        len--;
                }
        }
        /* converting binary to octal value */
        binaryToOctal(input);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your binary value: 111101100
  Equivalent Octal Value: 754



No comments:

Post a Comment