Google News
logo
C Program to Convert Binary to Octal Number System
In the following example of C program that converts a binary number to an octal number :
Program :
#include <stdio.h>
#include <math.h>

int main() {
    long long binary, octal = 0;
    int digits = 0;

    printf("Enter a binary number: ");
    scanf("%lld", &binary);

    while (binary != 0) {
        int digit = binary % 1000;
        int octal_digit = 0;

        // Convert the 3-digit binary number to an octal digit
        for (int i = 0; i < 3; i++) {
            octal_digit += (digit % 10) * pow(2, i);
            digit /= 10;
        }

        octal += octal_digit * pow(10, digits);
        digits++;
        binary /= 1000;
    }

    printf("The octal equivalent is %lld\n", octal);
    return 0;
}
Output :
Enter a binary number: 101024
The octal equivalent is 58
Explanation :

* We start by declaring three variables: binary to store the binary number, octal to store the octal equivalent, and digits to keep track of the number of digits in the octal number.

* We ask the user to enter a binary number using printf and scanf.

* We use a while loop to convert each 3-digit group of the binary number to an octal digit. The loop continues until the binary number becomes 0.

* Inside the loop, we get the rightmost 3-digit group of the binary number using the modulo operator %. We then convert this 3-digit binary number to an octal digit by multiplying each binary digit with the corresponding power of 2 (2^0, 2^1, or 2^2) and adding the results. We add this octal digit to the octal variable, multiplied by 10 raised to the current number of digits.

* We then divide the binary number by 1000 to remove the processed 3-digit group, and increment the digits variable by 1 to move to the next position in the octal number.

* After the loop, we print the octal variable as the octal equivalent using printf.

Note : This program assumes that the input binary number is valid (i.e., it only contains 0s and 1s). If the input is invalid or contains leading zeros, the program may produce unexpected results.