C program to Convert Binary to Octal number

In this article, we are going to learn how to convert a binary number to an Octal number. Here we are going to learn about two numbers one is binary and another is octal. Binary numbers are base 2 numbers and represented in 0s and 1s. Octal numbers are base 8 numbers and are represented in numbers from 0 to 7.

The binary to octal equivalent number table is given below. We are going to use this table in our program to convert the number.

Binary NumberOctal Number
0000
0011
0102
0113
1004
1015
1106
1117

C program to convert binary to octal number


In this example, Write a C program to input binary numbers from users and convert them to the octal number system. We are going to take the input from the user in the form of a binary number. Then we will start from the right side of this binary number and will collect 3-3 bits to find their octal equivalent. We will continue doing this until we process all the bits in the binary number.

#include <stdio.h>

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

    long long binNum;
    long long octalNum;
    long long temp;
    int ThreeDigitEquivalent;
    int index;

    octalNum = 0;
    index= 1;
    
    printf("Please enter 8 bit binary number: ");
    scanf("%lld", &binNum);

    temp = binNum;
    
    while(temp != 0)
    {
        ThreeDigitEquivalent = temp % 1000;

        for(int i=0; i<8; i++)
        {
            if(octTable[i] == ThreeDigitEquivalent)
            {
                octalNum = (i * index) + octalNum;
                break;
            }
        }
        temp /= 1000;

        index *= 10; 
    }

    printf("Octal Equivalent to Binary number = %lld is = %lld \n", binNum,octalNum);
    return 0;
}

Output

Please enter 8 bit binary number: 10101010
Octal Equivalent to Binary number = 10101010 is = 252