C program to convert Binary to Octal number system

Write a C program to read binary number from user and convert to octal number system. How to convert from binary number system to octal number system in C.

Example:
Input binary number: (00110111)2
Output octal number: (67)8

Required knowledge:

Basic C programming, For loop

Binary Number System:

Binary number system is a base 2 number system. Binary number system uses only 2 symbols to represent all its numbers i.e. 0 and 1.

Octal Number System:

Octal number system is a base 8 number system. Octal number system uses 8 symbols to represent all its numbers i.e. 0 1 2 3 4 5 6 7

Algorithm to convert Binary to Octal number system:

Conversion from binary to octal number system is very easy just follow these steps to convert any binary number to octal number.
Step 1: Group all binary number into 3 digits starting from right side.
Step 2: Write corresponding octal value for the grouped binary value.
Binary to Octal number conversion
Binary Octal
000 0
001 1
010 2
011 3
100 4
101 5
110 6
111 7


Program:

/**
 * C program to convert binary to octal number system
 */

#include <stdio.h>

int main()
{
    int octalConstant[] = {0, 1, 10, 11, 100, 101, 110, 111};

    long long binary, octal, tempBinary;
    int digit, count, i;

    octal = 0;
    count = 1;
    
    /*
     * Reads binary number from user
     */
    printf("Enter any binary number: ");
    scanf("%lld", &binary);

    /* Copies original binary value to temp variable */
    tempBinary = binary;
    
    /*
     * Finds the octal equivalent of binary value
     */ 
    while(tempBinary != 0)
    {
        digit = tempBinary % 1000;

        for(i=0; i<8; i++)
        {
            if(octalConstant[i] == digit)
            {
                octal = (i * count) + octal;
                break;
            }
        }

        tempBinary /= 1000;
        count *= 10;
    }

    printf("\nOriginal binary number = %lld\n", binary);
    printf("Octal number = %lld", octal);

    return 0;
}
Output
Enter any binary number: 11001111

Original binary number = 11001111
Octal number = 317

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment