#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;
}
Enter an octal number: 58
The binary equivalent is 101000
octal
number, binary to store the binary
equivalent, and power
to keep track of the current power of 1000.printf
and scanf
.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.%
. 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.power
variable by 1 to move to the next group of 3 binary digits.binary
variable as the binary equivalent using printf
.