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

int main() {
    int octal, binary = 0, power = 0;

    printf("Enter an octal number: ");
    scanf("%d", &octal);

    while (octal != 0) {
        int digit = octal % 10;

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

        binary += binary_digit * pow(1000, power);
        power++;
        octal /= 10;
    }

    printf("The binary equivalent is %d\n", binary);
    return 0;
}
Output :
Enter an octal number: 58
The binary equivalent is 101000
Explanation :

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

* We ask the user to enter an octal number using printf and scanf.

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

* Inside the loop, we get the rightmost digit of the octal number using the modulo operator %. We then convert this digit to a 3-digit binary number by repeatedly dividing it by 2 and adding the remainders (in reverse order) to the corresponding powers of 10 (10^0, 10^1, or 10^2). We add this binary number to the binary variable, multiplied by 1000 raised to the current power.

* We then divide the octal number by 10 to remove the rightmost digit, and increment the power variable by 1 to move to the next group of 3 binary digits.

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

Note : This program assumes that the input octal number is valid (i.e., it only contains digits from 0 to 7). If the input is invalid, the program may produce unexpected results.